我有一个买方和助理姓名的数据框,如下所示:
df = pd.DataFrame([
{ 'buyer': 'Lebron James', 'assistant': 'Lebron James' },
{ 'buyer': 'Jon Snow', 'assistant': 'Arya Stark' },
{ 'buyer': 'Frodo Baggins', 'assistant': 'Sam Gamyi' }
])
我想将买家的名字分为他们的名字和姓氏,所以预期的输出将是:
first_name surname Lebron James Jon Snow Frodo Baggings
为此,我定义了一个函数并尝试使用apply():
def first_name(row):
return df['buyer'][row].split()[0]
df['first_name'] = df.apply(first_name, axis = 1)
但是,出现以下错误:
Traceback (most recent call last):
File "<ipython-input-35-f3bcdf3bb991>", line 1, in <module>
df.apply(first_name, axis = 1)
File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 6487, in apply
return op.get_result()
File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 151, in get_result
return self.apply_standard()
File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 257, in apply_standard
self.apply_series_generator()
File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 286, in apply_series_generator
results[i] = self.f(v)
File "<ipython-input-32-410cb25f2482>", line 2, in first_name
return df['buyer'][row].split()[0]
File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 5067, in __getattr__
return object.__getattribute__(self, name)
AttributeError: ("'Series' object has no attribute 'split'", 'occurred at index 0')
我已经了解到,使用apply with axis = 1发送了行号作为参数,所以我不明白为什么它行不通。如果我手动将行号作为参数,它将按预期工作:
first_name(1)
最佳答案
df1 = df['buyer'].str.split(expand=True).rename(columns={0:'first_name',1:"surname"})
print(df1)
first_name surname
0 Lebron James
1 Jon Snow
2 Frodo Baggins
要么:
df = df.join(df1)
print(df)
assistant buyer first_name surname
0 Lebron James Lebron James Lebron James
1 Arya Stark Jon Snow Jon Snow
2 Sam Gamyi Frodo Baggins Frodo Baggins