gpt4 book ai didi

python - 根据另一列向日期添加一天

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

我有一个问题,我正在组合两个数据集,它们对午夜有不同的定义。因此,我想为每次出现的午夜向其中一个数据集添加一天,以便它们都遵循相同的日期设置。

我按以下方式安排了我的日期和时间:

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%m/%Y')
df['Hour'] = pd.to_datetime(df['Hour']).dt.strftime('%H:%M')

然后我试图修改任何出现的 00:00:00 以使其晚一天:

df.loc['Hour' == '00:00:00', 'Date'] = pd.DatetimeIndex(df.Date) + timedelta(days=1)

但是我不断提出一个 KeyError:

raise KeyError("cannot use a single bool to index into setitem")
KeyError: 'cannot use a single bool to index into setitem

如有任何帮助,我们将不胜感激。

目标:输入:

Date        |  Hour
---------------------
19/06/2016 | 23:30
19/06/2016 | 23:45
19/06/2016 | 00:00
20/06/2016 | 00:15
20/06/2016 | 00:30

输出:

    Date        |  Hour
---------------------
19/06/2016 | 23:30
19/06/2016 | 23:45
20/06/2016 | 00:00
20/06/2016 | 00:15
20/06/2016 | 00:30

最佳答案

您可以使用 mask检查午夜并添加一天:

f['Date'] = pd.to_datetime(f['Date'])
m = f['Hour'] == '00:00'
f['Date'] = f['Date'].mask(m, f['Date'] + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y')

loc 的解决方案:

m = f['Hour'] == '00:00'
dates = pd.to_datetime(f['Date'])
f.loc[m, 'Date'] = (dates + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y')
#alternative
#f.loc[m, 'Date'] = (dates[m] + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y')

解决方案 numpy.where :

m = f['Hour'] == '00:00'
dates = (pd.to_datetime(f['Date']) + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y')
f['Date'] = np.where(m, dates, f['Date'])

print (f)
Date Hour
0 19/06/2016 23:30
1 19/06/2016 23:45
2 20/06/2016 00:00
3 20/06/2016 00:15
4 20/06/2016 00:30

代码内:

for fname in glob.glob(path):
fname = fname.replace(r'\2016', '/2016')
f = pd.DataFrame(pd.read_csv(fname))
f = f.replace({'Hour': {'24:00:00': '00:00'}})
f['Date'] = pd.to_datetime(f['Date']).dt.strftime('%d/%m/%Y')
f['Hour'] = pd.to_datetime(f['Hour']).dt.strftime('%H:%M')

m = f['Hour'] == '00:00'
dates = (pd.to_datetime(f['Date']) + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y')
f['Date'] = np.where(m, dates, f['Date'])

print(fname)
if a == 0:
f_2016['Date'] = f['Date']
f_2016['Hour'] = f['Hour']
a = 1
f_2016 = pd.merge(f_2016, f, on=['Date', 'Hour'])
print(pd.DataFrame.head(f_2016, n=100))

关于python - 根据另一列向日期添加一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49408660/

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