我有一个熊猫系列:
names = pd.Series([
'Andre Agassi',
'Barry Bonds',
'Christopher Columbus',
'Daniel Defoe',
'Emilio Estevez',
'Fred Flintstone',
'Greta Garbo',
'Humbert Humbert',
'Ivan Ilych'])它看起来像这样:
0 Andre Agassi
1 Barry Bonds
2 Christopher Columbus
3 Daniel Defoe
4 Emilio Estevez
5 Fred Flintstone
6 Greta Garbo
7 Humbert Humbert
8 Ivan Ilych我想这样做:
0 Agassi, Andre
1 Bonds, Barry
2 Columbus, Christopher
3 Defoe, Daniel
4 Estevez, Emilio
5 Flintstone, Fred
6 Garbo, Greta
7 Humbert, Humbert
8 Ilych, Ivan有人建议这样的代码,但它不起作用...
names.apply(split)[1]+', ' + names.apply(split)[0]我检查了以下帖子,但它们似乎也不是我想要的:
发布于 2017-02-12 23:34:09
使用和不使用str.replace
In [451]: names.str.split().apply(lambda x: ', '.join(x[::-1]))
Out[451]:
0 Agassi, Andre
1 Bonds, Barry
2 Columbus, Christopher
3 Defoe, Daniel
4 Estevez, Emilio
5 Flintstone, Fred
6 Garbo, Greta
7 Humbert, Humbert
8 Ilych, Ivan
dtype: object
In [452]: names.apply(lambda x: ', '.join(x.split()[::-1]))
Out[452]:
0 Agassi, Andre
1 Bonds, Barry
2 Columbus, Christopher
3 Defoe, Daniel
4 Estevez, Emilio
5 Flintstone, Fred
6 Garbo, Greta
7 Humbert, Humbert
8 Ilych, Ivan
dtype: object发布于 2017-02-13 00:08:08
矢量化的Numpy解决方案:
In [276]: arr = names.str.split(expand=True).values[:, ::-1]
In [277]: names.values[:] = np.sum(np.insert(arr, 1, ', ', axis=1), axis=1)
In [278]: names
Out[278]:
0 Agassi, Andre
1 Bonds, Barry
2 Columbus, Christopher
3 Defoe, Daniel
4 Estevez, Emilio
5 Flintstone, Fred
6 Garbo, Greta
7 Humbert, Humbert
8 Ilych, Ivan
dtype: object发布于 2017-02-12 23:32:32
将.map与字符串方法结合使用,如下所示:
names.map(lambda s: s.split()[1] + ', ' + s.split()[0])https://stackoverflow.com/questions/42189469
复制相似问题