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

时间:2017-12-23 15:35:41

标签: python python-3.x pandas dataframe

我有两个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

3 个答案:

答案 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)

使用combine_firstfillna

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)

mask

怎么样?
df1['b'].update(df2.mask(df2=='')['update'])


>>> df1
     a    b
0  aaa  eee
1  bbb    X
2  ccc  ggg
3  ddd    Y