Рассчитать вычитание двух столбцов в двух информационных кадрах путем замены. - PullRequest
3 голосов
/ 25 февраля 2020

У меня есть df1, который содержит:

IDs    values
E21    32
DD12   82
K99    222

И df2, который содержит:

IDs   values
GU1   87
K99   93
E21   48

Мне нужно проверить, является ли ID в df2 существует в df1, для этого ID вычтите value из df1 - df2 и обновите value в df2.

Если ID из df2 не существует в df1, значение для этого ID в df2 остается неизменным.

Итак, результат из приведенного выше примера (в основном df2 будет обновлен) :

IDs    values
GU1    87 #the same not changed since it not exist in df1
K99    129 #exist in df1, do the subtraction 222-93=129
E21    -16 #exist in df1, do the subtraction 32-48=129

Любая помощь, пожалуйста?

Ответы [ 4 ]

2 голосов
/ 26 февраля 2020
# create new column in df2 with name 'new'
df2['new'] = df2['values']
# loop on the values of 'IDs' column
for i, element in enumerate(df2.IDs):
    # condition to check if an element exists in df1  
    if element in df1.IDs.values:
        df2['new'][i]  = df1['values'][df1.index[df1.IDs == element][0]] - df2['values'][i]
# drop the old values column 
df2.drop('values', axis = 1, inplace= True)
# rename the new values column
df2.rename(columns={'new': 'values'}, inplace= True)  
1 голос
/ 25 февраля 2020

IIU C:

d = df1.set_index('IDs')['values']
i = df2.itertuples(index=False)
df2.assign(values=[d[x] - v if x in d.index else v for x, v in i])

   IDs  values
0  GU1      87
1  K99     129
2  E21     -16

Та же самая идея, но с использованием dict вместо pandas.Series

d = dict(zip(df1['IDs'], df1['values']))
i = df2.itertuples(index=False)
df2.assign(values=[d[x] - v if x in d else v for x, v in i])
1 голос
/ 26 февраля 2020

Вы можете использовать метод update:

df2.update(df1 - df2)

Вывод:

     values
IDs        
GU1    87.0
K99   129.0
E21   -16.0
1 голос
/ 25 февраля 2020

Вот способ использования pd.merge:

# merge the data frames
dfx = pd.merge(df2, df1, on='IDs', how='left', suffixes=('','_2'))

# modify new columns
dfx['val'] = dfx['values_2'] - dfx['values']
dfx['val'] = dfx['val'].combine_first(dfx['values'])
dfx = dfx[['IDs','val']].rename(columns={'val':'values'})

print(dfx)

   IDs  values
0  GU1    87.0
1  K99   129.0
2  E21   -16.0
...