pandas 得到偶数奇数行差并与其他列合并

bjg7j2ky  于 2023-04-28  发布在  其他
关注(0)|答案(2)|浏览(131)

我想得到偶数和奇数行之间的差异,然后添加奇数行ts值以及。
当前的实现方式确实正确地不同,但是遗漏了奇数行ts值。

import pandas as pd

data = [
    ['04-21 10:45:21.718'],
    ['04-21 10:45:22.718'],
    ['04-21 10:45:24.718'],
    ['04-21 10:45:28.718'],
    ['04-21 10:45:32.718'],
    ['04-21 10:45:38.718']
    ]

df = pd.DataFrame(data,columns=['ts'])
df['ts'] = pd.to_datetime(df['ts'],format="%m-%d %H:%M:%S.%f")
print(df)

df2 = pd.DataFrame(df['ts'].values[1::2] - df['ts'].values[::2],columns=['delta'])
df2['delta'] = df2['delta'].dt.total_seconds()
print(df2)

电流输出:

ts
0 1900-04-21 10:45:21.718
1 1900-04-21 10:45:22.718
2 1900-04-21 10:45:24.718
3 1900-04-21 10:45:28.718
4 1900-04-21 10:45:32.718
5 1900-04-21 10:45:38.718
   delta
0    1.0
1    4.0
2    6.0

预期输出:

ts  delta
1 1900-04-21 10:45:22.718    1.0
2 1900-04-21 10:45:28.718    4.0
3 1900-04-21 10:45:38.718    6.0
oalqel3c

oalqel3c1#

尝试:

df2 = df.assign(delta=df['ts'].diff().dt.total_seconds()).iloc[1::2]

输出:

ts  delta
1 1900-04-21 10:45:22.718    1.0
3 1900-04-21 10:45:28.718    4.0
5 1900-04-21 10:45:38.718    6.0
o8x7eapl

o8x7eapl2#

下面是使用groupby()的方法

df.groupby(df.index//2)['ts'].agg(ts = 'first',delta = lambda x: (x.iloc[-1] - x.iloc[0]).total_seconds())

输出:

ts  delta
0 1900-04-21 10:45:21.718    1.0
1 1900-04-21 10:45:24.718    4.0
2 1900-04-21 10:45:32.718    6.0

相关问题