如何将pandas DataFrame与内置逻辑连接起来?

Mic*_*ael 3 python dataframe python-3.x pandas

我有两个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']})
Run Code Online (Sandbox Code Playgroud)

我试图应用一些连接逻辑,但这不会产生预期的输出.

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
Run Code Online (Sandbox Code Playgroud)

从这个输出我可以产生预期的输出,但我想知道这个逻辑是否可以直接在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
Run Code Online (Sandbox Code Playgroud)

Flo*_*oor 5

使用ie update替换'' 使用内置nan

df1['b'].update(df2['update'].replace('',np.nan))

    a    b
0  aaa  eee
1  bbb    X
2  ccc  ggg
3  ddd    Y
Run Code Online (Sandbox Code Playgroud)

你也可以使用np.whereie

out = df1.assign(b=np.where(df2['update'].eq(''), df2['b'], df2['update']))
Run Code Online (Sandbox Code Playgroud)