gpt4 book ai didi

python - pandas 更新选定的列并跟踪更改日期

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:44 24 4
gpt4 key购买 nike

我有两个数据帧,需要用第二个数据帧中的相应值更新第一个数据帧中的某些列,然后更改日期列以反射(reflect)发生的更改。

today = datetime.datetime.today().date()

df1 = pd.DataFrame([['alpha','foo','buzz','fox',datetime.date(2017,5,31),np.nan],['Beta','foo','flop','cat',datetime.date(2017,8,11),datetime.date(2017,9,19)],
['Gamma','bar','honk','sheep',datetime.date(2017,8,12),np.nan],['omega','bar','growl','dog',datetime.date(2017,2,23),datetime.date(2017,3,2)]],
columns = ['type','col1','col2','enteredCol','CreationDate','lastUpdateDate']).set_index(['type'])

print df1

col1 col2 enteredCol CreationDate lastUpdateDate
type
alpha foo buzz fox 2017-05-31 NaN
Beta foo flop cat 2017-08-11 2017-09-19
Gamma bar honk sheep 2017-08-12 NaN
omega bar growl dog 2017-02-23 2017-03-02


df2 = pd.DataFrame([['alpha','bar','buzz'],['Beta','foo','twist'],['Gamma','bar','honk']], columns = ['type','col1','col2']).set_index(['type'])

print df2
col1 col2
type
alpha bar buzz
Beta foo twist
Gamma bar honk

如果df2中的col1或col2不同,我需要更新df1中的相应值。如果进行更改,则需要将lastUpdateDate设置为今天的日期

#run update on col1 and col2 - if updated, change lastUpdateDate to today's date

print df_out

col1 col2 enteredCol CreationDate lastUpdateDate
type
alpha bar buzz fox 2017-05-31 2017-10-31
Beta foo twist cat 2017-08-11 2017-10-31
Gamma bar honk sheep 2017-08-12 NaN
omega bar growl dog 2017-02-23 2017-03-0

关于如何做到这一点的想法?我可以手动合并每个更改的列并进行比较,但有很多列我需要检查。 df.update() 没有提供一种方法来注意值已更改,或者我也可以使用它。

最佳答案

使用combine_first,然后使用 bool 索引:

df_out = df2.combine_first(df1)

df_out.loc[~df1[['col1','col2']].eq(df_out[['col1','col2']]).all(1),'lastUpdateDate'] = today

print(df_out)

输出:

      CreationDate col1   col2 enteredCol lastUpdateDate
type
Beta 2017-08-11 foo twist cat 2017-10-31
Gamma 2017-08-12 bar honk sheep NaN
alpha 2017-05-31 bar buzz fox 2017-10-31
omega 2017-02-23 bar growl dog 2017-03-02

关于python - pandas 更新选定的列并跟踪更改日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com