如何用另一列列表中的特定元素填充数据框中的空列?

时间:2018-08-29 14:29:14

标签: python pandas

具有由人和顺序组成的数据框...

person     order                                 elements
Alice      [drink, snack, salad, fish, dessert]  5          
Tom        [drink, snack]                        2          
John       [drink, snack, soup, chicken]         4          
Mila       [drink, snack, soup]                  3          

我想知道顾客主要吃什么。因此,我想添加另一列[main_meal],使其成为我的df。

person     order                               elements   main_meal
Alice      [drink, snack, salad, fish, dessert]  5          fish
Tom        [drink, snack]                        2          none
John       [drink, snack, soup, chicken]         4          chicken
Mila       [drink, snack, soup]                  3          none

规则是,如果客户订购了4餐或更多餐,则意味着第4个元素始终是主菜,因此我想从订单列上的列表中提取第4个元素。如果它包含少于4个元素,则将'main_meal'分配为没有。我的代码:

df['main_meal'] = ''
if df['elements'] >= 4:
     df['main_meal'] = df.order[3]
else:
     df['main_meal'] = 'none'

它不起作用:

 ValueError                                Traceback (most recent call last)
 <ipython-input-100-39b7809cc669> in <module>()
     1 df['main_meal'] = ''
     2 df.head(5)
 ----> 3 if df['elements'] >= 4:
       4     df['main_meal'] = df.order[3]
       5 else:

 ~\Anaconda\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
 1571         raise ValueError("The truth value of a {0} is ambiguous. "
 1572                          "Use a.empty, a.bool(), a.item(), a.any() or 
 a.all()."
 -> 1573                          .format(self.__class__.__name__))
 1574 
 1575     __bool__ = __nonzero__

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我的代码有什么问题?

3 个答案:

答案 0 :(得分:4)

使用str方法进行切片

In [324]: df['order'].str[3]
Out[324]:
0       fish
1        NaN
2    chicken
3        NaN
Name: order, dtype: object

In [328]: df['main_meal'] = df['order'].str[3].fillna('none')

In [329]: df
Out[329]:
  person                                 order  elements main_meal
0  Alice  [drink, snack, salad, fish, dessert]         5      fish
1    Tom                        [drink, snack]         2      none
2   John         [drink, snack, soup, chicken]         4   chicken
3   Mila                  [drink, snack, soup]         3      none

答案 1 :(得分:1)

对于小型数据框,可以按照@Zero's solution使用str访问器。对于较大的数据框,您可能希望使用NumPy表示形式创建一个序列:

# Benchmarking on Python 3.6, Pandas 0.19.2

df = pd.concat([df]*100000)

%timeit pd.DataFrame(df['order'].values.tolist())[3]  # 125 ms per loop
%timeit df['order'].str[3]                            # 185 ms per loop

# check results align
x = pd.DataFrame(df['order'].values.tolist())[3].fillna('None').values
y = df['order'].str[3].fillna('None').values
assert (x == y).all()

答案 2 :(得分:0)

您还可以使用apply和lambda函数。

df['main_meal'] = df['order'].apply(lambda r: r[3] if len(r) >= 4 else 'none')

对于大型数据集,它的回答要慢于@jpp's,但对于较小的数据集,它的回答要快(且更冗长),比@jpp和@Zero's都要快(请注意,我添加了.fillna(),因此它们返回了结果相同):

%timeit df['order'].apply(lambda r: r[3] if len(r) >= 4 else 'none')  # 242 µs
%timeit pd.DataFrame(df['order'].values.tolist())[3].fillna('none')  # 1.17 ms
%timeit df['order'].str[3].fillna('none')  # 487 µs

# Large dataset
df = pd.concat([df]*100000)

%timeit df['order'].apply(lambda r: r[3] if len(r) >= 4 else 'none')  # 118ms
%timeit pd.DataFrame(df['order'].values.tolist())[3].fillna('none')  # 51.8ms
%timeit df['order'].str[3].fillna('none')  # 309ms

如果您检查它们的值,它们将匹配。

x = df['order'].apply(lambda r: r[3] if len(r) >= 4 else 'none')
y = pd.DataFrame(df['order'].values.tolist())[3].fillna('none')
z = df['order'].str[3].fillna('none')

(x.values == y.values).all()  # True
(x.values == z.values).all()  # True

Python 3.6.6 |熊猫0.23.4