我需要计算两个日期之间的差异,但我需要对每对行进行计算,然后将其保存在 Excel 文件中,例如:
df:
B
0 2018-02-11 12:14:25 #1st row
1 2018-02-11 12:15:30 #2nd row
2 2018-02-11 12:15:54 #3rd row
3 2018-02-11 12:16:11 #4th row
我的程序需要从第一行减去第二行,从第三行减去第四行。
这是我到目前为止的代码:
import pandas as pd
df = pd.read_excel('test.xlsx',header=0, index= False)
sub ='chan_avail'
df["Indexes"]= df["A"].str.find(sub)
df["B"]=df['Time'].where(df['Indexes'] == 0)
df1 = df.dropna(subset=['B'])
#print(df1)
df2 = df1.reset_index(drop=True, inplace=True)
df1['B'] = pd.to_datetime(df1['B'])
#print(df1)
xx=len(df1.index)
for i in range(xx):
if i % 2 == 0:
print('!!') #test
df1['diffB'] = df1['B'] - df1['B'].shift(-1)
print(df1)
df1.to_excel('output.xlsx', 'Sheet1', index=True)
我的目的是计算行之间的差异(如果索引是对的),但它不起作用。
另外,当我尝试在 Excel 中保存时间差时,我得到了 0,但在 python 的控制台中,我得到了正确的值,但如果我添加 df1['diffB'] = pd.to_datetime(df1['diffB'])
我得到的结果不正确。
感谢您的帮助。
最佳答案
您可以对奇数和偶数值进行切片,并将一个系列转换为 numpy 数组以避免对齐 - 这意味着为了正确减去,必须将两个或其中一个中的相同索引值转换为数组:
df['B'] = pd.to_datetime(df['B'])
df['diffB'] = df['B'].iloc[1::2] - df['B'].iloc[::2].to_numpy()
print (df)
B diffB
0 2018-02-11 12:14:25 NaT
1 2018-02-11 12:15:30 00:01:05
2 2018-02-11 12:15:54 NaT
3 2018-02-11 12:16:11 00:00:17
或者:
df['diffB'] = df['B'].iloc[1::2].to_numpy() - df['B'].iloc[::2]
print (df)
B diffB
0 2018-02-11 12:14:25 00:01:05
1 2018-02-11 12:15:30 NaT
2 2018-02-11 12:15:54 00:00:17
3 2018-02-11 12:16:11 NaT
如果行数也是奇数,则解决方案有效:
df['B'] = pd.to_datetime(df['B'])
df['diffB'] = df.groupby(np.arange(len(df)) // 2)['B'].shift(-1) - df['B']
print (df)
B diffB
0 2018-02-11 12:14:25 00:01:05
1 2018-02-11 12:15:30 NaT
2 2018-02-11 12:15:54 00:00:17
3 2018-02-11 12:16:11 NaT
关于python - 如何使用 Python 减去数据框中每对行的日期并将其保存在 Excel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888254/