如果pandas数据框列中的值存在于另一个数据框中,则更新它们

时间:2018-10-07 15:07:19

标签: python pandas dataframe series

我有两个数据框,第一个具有所有值,但是其中一些是旧的,而第二个只有一些值,但是它们是新的。我想做的是用第二个数据框中的值更新第一个数据框中的值(如果存在)。

df_a
   A  B
0  a  1
1  b  2
2  c  3
3  d  4
4  e  5
5  f  6
6  g  7
7  h  8
8  i  9

df_b
   A  B
0  a  9
1  c  6
2  e  4

我想要的结果是:

df_a
   A  B
0  a  9
1  b  2
2  c  6
3  d  4
4  e  4
5  f  6
6  g  7
7  h  8
8  i  9

我如何做到这一点,希望没有循环?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以通过set_index构造一个序列,然后使用map + fillna来更新值:

s = df_b.set_index('A')['B']
df_a['B'] = df_a['A'].map(s).fillna(df_a['B']).astype(int)

print(df_a)

   A  B
0  a  9
1  b  2
2  c  6
3  d  4
4  e  4
5  f  6
6  g  7
7  h  8
8  i  9

答案 1 :(得分:0)

有几种方法可以完成

# options 1 and 2 use numpy
import numpy as np

# 1
# use numpy isin and numpy searchsorted functions
mask = np.isin(df_a.A, df_b.A)
df_a.B.values[mask] = \
    df_b.B.values[np.searchsorted(df_b.A.values,
                                  df_a.A.values[mask])]

# -----------------------------------------------------------------
# using pandas merge for next 3 methods:
merged = df_a.merge(df_b, on='A', how='outer',
                    suffixes=('_dfa', '_dfb'))

# 2
# use numpy where to fill in with df_a["B"] values
df_a['B'] = np.where(merged['B_dfb'].isnull(),
                     merged['B_dfa'],
                     merged['B_dfb']).astype(int)

# 3
# same as above but use pandas series where to fill values
df_a['B'] = merged.B_dfa.where(merged['B_dfb'].isnull(),
                               merged['B_dfb']).astype(int)

# 4
# use series fillna
df_a['B'] = merged['B_dfb'].fillna(merged['B_dfa']).astype(int)

#----------------------------------------------------------------
# for next 2 methods, make "A" column indexed
# dataframes from df_a, df_b
a = df_a.set_index('A')
b = df_b.set_index('A')

# 5
# using pandas dataframe update
a.update(b)
df_a['B'] = a['B'].values.astype(int)

# 6
# using pandas auto-align by index and pandas series where

# using pandas auto-align to index,
# add dataframe b "B" values to dataframe a (df_a indexed with column "A")
a['C'] = b['B']
# using pandas series where, fill in values from a["B"] and
# assign to df_a["B"]
df_a['B'] = a['C'].where(~a['C'].isnull(), a['B']).values.astype(int)
# or use pandas series fillna
df_a['B'] = a['C'].fillna(a['B']).values.astype(int)

# --------------------------------------------------------------------

# 7
# slightly modified version of accepted answer avoiding setting index
df_a['B'] = df_a['A'].map(dict(df_b.values)).fillna(df_a['B']).astype(int)