python - 提取 DataFrame 列中的最后一个单词

标签 python pandas list

这一定很简单 - 但我无法弄清楚。我在 DataFrame 中有一个“名称”列,我试图将 ['名字'、'中间名'、'姓氏'] 的顺序反转为 ['姓氏'、'名字'、'中间名姓名']。

这是我的代码:

for i in range(2114):
bb = a['Approved by User'][i].split(" ",2)[2]
aa = a['Approved by User'][i].split(" ",2)[0]
a['Full Name]'] = bb+','+aa

不幸的是,我不断收到 IndexError: list index out of range with the current code。

这就是我想要的:

旧列名称|杰西卡·玛丽·辛普森

新列名称|辛普森杰西卡玛丽

最佳答案

一种方法是分割字符串,然后在函数中加入它。 像这样:

import pandas as pd

d = {"name": ["Jessica Mary Simpson"]}

df = pd.DataFrame(d)
a = df.name.str.split()
a = a.apply(lambda x: " ".join(x[::-1])).reset_index()
print(a)

输出:

    index   name
0   0   Simpson Mary Jessica

关于python - 提取 DataFrame 列中的最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67227693/

相关文章:

Python 3 哈希 HMAC-SHA512

python : How to create columns from words occurred in a column?

java - 在可迭代接口(interface)中使用比较器作为默认方法进行排序

Pandas 面板申请: getting current index

python - 将字典值转换为值列表 python

C++ list::sort <未解析的重载函数类型>

python - 不同数据帧列中列出的不同缺失值将替换为 NaN

python - 使用 reduce 时对象没有属性(但在 map 上有效)

python - Django聚合函数问题(Count = -number-)

python - Pandas:如何根据多列的条件将值替换为 np.nan