申请熊猫根据行不起作用

时间:2019-05-31 10:13:28

标签: python pandas split apply

我有一个买方和助理姓名的数据框,如下所示:

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)

2 个答案:

答案 0 :(得分:1)

要回答您的问题,您可以使用:

def first_name(x):
    return x.split()[0]
df['first']=df.buyer.apply(first_name)
print(df)

      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo

但是,正如@Sandeep指出的那样,您还应该将内置的熊猫解决方案视为series.str.split(),您可以使用df.assign()直接分配该列

df=df.assign(first=df.buyer.str.split().str[0])

      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo

答案 1 :(得分:1)

使用Series.str.split

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