首页 > 解决方案 > 根据来自另一列的信息用 pandas 填充一个空列

问题描述

我正在尝试根据另一列的信息填充一个空列

我的数据框

   A        B                                    C
0  F    House                     Are you at home?
1  E    House    description: to deliver tomorrow
2  F    Apt                 Here is some exemples 
3  F    House          description: a brown table
4  E    Apt               description: in the bus
5  F    House                 Hello, how are you?
6  E    Apt                     description: keys

所以,我创建了一个 D 列,如果 C 列以“描述”开头,我填写“模糊”,如果不是“嗡嗡”。

new_column['D'] = ''

我试着填满它们

def fill_column(delete_column):
    if new_column['D'].loc[new_column['D'].str.startswith('description:'):
        new_column['D'] == 'fuzzy'
    else:
        new_column['D'] == 'buzzy'

    return new_column

我的输出:

  File "<ipython-input-41-ec3c1407168c>", line 6
    else:
       ^
SyntaxError: invalid syntax

良好的输出:

   A        B                                   C       D
0  F    House                    Are you at home?   buzzy
1  E    House    description: to deliver tomorrow   fuzzy
2  F    Apt                 Here is some exemples   buzzy
3  F    House          description: a brown table   fuzzy
4  E    Apt               description: in the bus   fuzzy
5  F    House                 Hello, how are you?   buzzy
6  E    Apt                     description: keys   fuzzy

标签: pythonpandas

解决方案


您在这里不需要if-else语句,您可以使用以下命令在一行中干净地完成此操作np.where

df['D'] = np.where(
    df['C'].str.startswith('description:'), 'fuzzy', 'buzzy')

您可以通过一次loc调用来完成此操作,因为您只分配了两个值。

df['D'] = 'buzzy'
df.loc[df['C'].str.startswith('description:'), 'D'] = 'fuzzy'

或者使用df.mask/df.where喜欢评论中建议的@jpp:

df['D'] = 'buzzy'
df['D'] = df['D'].mask(df['C'].str.startswith('description:'), 'fuzzy')

最后,使用map

m = {True: 'fuzzy', False: 'buzzy'}
df['D'] = df['C'].str.startswith('description:').map(m)

print(df)
   A      B                                 C      D
0  F  House                  Are you at home?  buzzy
1  E  House  description: to deliver tomorrow  fuzzy
2  F    Apt             Here is some exemples  buzzy
3  F  House        description: a brown table  fuzzy
4  E    Apt           description: in the bus  fuzzy
5  F  House               Hello, how are you?  buzzy
6  E    Apt                 description: keys  fuzzy

推荐阅读