根据另一只熊猫的值自动填充栏

时间:2018-08-17 03:58:01

标签: python pandas where

我正在尝试根据另一个值填充单独的列。对于下面的df,我想在['Assign']'C1'时用['Code'] == 'A'填充'C2' when ['Code'] == 'B'。我想用np.nan

填充的所有其他内容

将熊猫作为pd导入

d = ({
    'Place' : ['Home','Away','Work','Home','Shops','Park','Cafe','Shops','Away','Home','Cafe','Work','Park'],  
    'Code' : ['A','A','A','A','C','B','B','C','A','A','B','A','B'],            
     })

df = pd.DataFrame(data=d)

我已经尝试过,但是值不正确。

df['Assign'] = df['Code'].where((df['Code'] == 'A'), ['C1'])
df['Assign'] = df['Code'].where((df['Code'] == 'B'), ['C2'])

我希望输出:

    Place Code Assign
0    Home    A     C1
1    Away    A     C1
2    Work    A     C1
3    Home    A     C1
4   Shops    C     
5    Park    B     C2
6    Cafe    B     C2
7   Shops    C     
8    Away    A     C1
9    Home    A     C1
10   Cafe    B     C2
11   Work    A     C1
12   Park    B     C2

2 个答案:

答案 0 :(得分:2)

您可以使用np.where

import numpy as np
df['Assign'] = np.where(df['Code']=='A','C1','C2')

根据当前有问题的更改,解决方案是:

df['Assign'] = np.where(df['Code']=='A','C1',np.where(df['Code']=='B','C2',''))

如果df['Code']=='C'使用时想要空值:

df['Assign'] = np.where(df['Code']=='A','C1',np.where(df['Code']=='B','C2',None))

None是字符串的空值。

答案 1 :(得分:1)

map与字典get方法和默认值一起使用

m = lambda x: dict(A='C1', B='C2').get(x, '')
df.assign(Assign=df.Code.map(m))

    Place Code Assign
0    Home    A     C1
1    Away    A     C1
2    Work    A     C1
3    Home    A     C1
4   Shops    C       
5    Park    B     C2
6    Cafe    B     C2
7   Shops    C       
8    Away    A     C1
9    Home    A     C1
10   Cafe    B     C2
11   Work    A     C1
12   Park    B     C2

fillna

m = dict(A='C1', B='C2')
df.assign(Assign=df.Code.map(m).fillna(''))