我有两个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
答案 0 :(得分:5)
使用内置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']))
答案 1 :(得分:3)
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。
答案 2 :(得分:3)
df1['b'].update(df2.mask(df2=='')['update'])
>>> df1
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y