我有两个pandas数据框,我想生成expected
数据框中显示的输出。
import pandas as pd
df1 = pd.DataFrame({'a':['aaa', 'bbb', 'ccc', 'ddd'],
'b':['eee', 'fff', 'ggg', 'hhh']})
df2 = pd.DataFrame({'a':['aaa', 'bbb', 'ccc', 'ddd'],
'b':['eee', 'fff', 'ggg', 'hhh'],
'update': ['', 'X', '', 'Y']})
expected = pd.DataFrame({'a': ['aaa', 'bbb', 'ccc', 'ddd'],
'b': ['eee', 'X', 'ggg', 'Y']})
我试图应用一些连接逻辑,但这不会产生预期的输出。
df1.set_index('b')
df2.set_index('update')
out = pd.concat([df1[~df1.index.isin(df2.index)], df2])
print(out)
a b update
0 aaa eee
1 bbb fff X
2 ccc ggg
3 ddd hhh Y
从这个输出我可以产生预期的输出,但我想知道这个逻辑是否可以直接在concat
调用内建立?
def fx(row):
if row['update'] is not '':
row['b'] = row['update']
return row
result = out.apply(lambda x : fx(x),axis=1)
result.drop('update', axis=1, inplace=True)
print(result)
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y
使用内置update
替换''与nan
即
df1['b'].update(df2['update'].replace('',np.nan))
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y
你也可以使用np.where
out = df1.assign(b=np.where(df2['update'].eq(''), df2['b'], df2['update']))
df1['b'] = df2['update'].mask(lambda x: x=='').combine_first(df1['b'])
#alternative
#df1['b'] = df2['update'].mask(lambda x: x=='').fillna(df1['b'])
print (df1)
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y
但是在DataFrame
s中必须使用相同的指数值。
与mask怎么样
df1['b'].update(df2.mask(df2=='')['update'])
>>> df1
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y