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

问题描述 投票:3回答:3

我有两个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
python python-3.x pandas dataframe
3个回答
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']))

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

但是在DataFrames中必须使用相同的指数值。


3
投票

mask怎么样

df1['b'].update(df2.mask(df2=='')['update'])


>>> df1
     a    b
0  aaa  eee
1  bbb    X
2  ccc  ggg
3  ddd    Y
© www.soinside.com 2019 - 2024. All rights reserved.