gpt4 book ai didi

python - Applymap 接口(interface)用于对多个(两个)列进行操作

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:09 26 4
gpt4 key购买 nike

假设我有一个 DataFrame:

df = pd.DataFrame({'DATE_1':['2010-11-06', '2010-10-07', '2010-09-07', '2010-05-07'],
'DATE_2':['2010-12-07', '2010-11-06', '2010-10-07', '2010-08-06']})
df['DATE_1'] = pd.to_datetime(df['DATE_1'])
df['DATE_2'] = pd.to_datetime(df['DATE_2'])

看起来像:

      DATE_1      DATE_2
0 2010-11-06 2010-12-07
1 2010-10-07 2010-11-06
2 2010-09-07 2010-10-07
3 2010-05-07 2010-08-06

我想创建另一列 DIFF,它是 DATE_2DATE_1 的天数、月数或年数差异。
我想要一个像在这些词下面的界面,因为我必须创建很多列,类似从 很多 DATE_X 列到 DIFF:

def date_diffrence(x, y, parameter):
if !np.isnan(x):
return (x-y)
df['DIFF'] = df.apply(date_diffrence(df['DATE_2'], df['DATE_1']))

根据这篇文章:Difference between map, applymap and apply methods in Pandas ,在我看来,我无法创建这样一个通用界面。我说得对吗?

最佳答案

看来您需要的函数没有applySeries(df 的列)作为dt.days 的参数:

def date_diffrence_days(x, y):
return (x-y).dt.days

df['DIFF'] = date_diffrence_days(df['DATE_2'], df['DATE_1'])
print (df)
DATE_1 DATE_2 DIFF
0 2010-11-06 2010-12-07 31
1 2010-10-07 2010-11-06 30
2 2010-09-07 2010-10-07 30
3 2010-05-07 2010-08-06 91

什么是相同的:

df['DIFF'] = (df['DATE_2'] - df['DATE_1']).dt.days
print (df)
DATE_1 DATE_2 DIFF
0 2010-11-06 2010-12-07 31
1 2010-10-07 2010-11-06 30
2 2010-09-07 2010-10-07 30
3 2010-05-07 2010-08-06 91

编辑:

def date_diffrence_days(x, y, parameter):
if parameter == 'm':
return (x-y).dt.days
elif parameter == 's':
return (x-y).dt.total_seconds()

df['DIFF'] = date_diffrence_days(df['DATE_2'], df['DATE_1'], 's')
print (df)
DATE_1 DATE_2 DIFF
0 2010-11-06 2010-12-07 2678400.0
1 2010-10-07 2010-11-06 2592000.0
2 2010-09-07 2010-10-07 2592000.0
3 2010-05-07 2010-08-06 7862400.0

关于python - Applymap 接口(interface)用于对多个(两个)列进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43208986/

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