我有两个这样的数据帧:
df1:
col1 col2 time
0 A A_1 05:02:03
1 A A_2 15:36:14
2 A A_1 28:21:47
3 A A_1 47:21:17
4 A A_1 32:28:01
5 A A_2 37:27:14
我想比较一下列";时间";是<24小时,>24,但是<48,>48,但是<72小时和>72,并将这些结果放入另一个数据帧中,如下所示:
df2:
col1 col2 time <24 24<time<48 48<time<72 time>72
0 A A_1 1 3 NaN NaN
1 A A_2 1 1 NaN NaN
所以,基本上,在这个df2中,我想要的是有满足比较的文件的计数,比如在"中有三个文件;时间";列,并且时间是24<时间<48,而我们只在";24<时间<48〃;柱
我尝试了@Andreas的这个代码,但如果没有时间,它就会失败;时间";列48<时间<72和时间>72:
df['day'] = (df['time'].str.split(':').str[0].astype(int)/24).astype(int)
df = df.pivot_table(index=['col1', 'col2'], columns=['day'], values=['time'], aggfunc='count').reset_index()
d = {'time0':'time <24', 'time1':'24<time<48', 'time2':'48<time<72', 'time3':'time>72'}
df.columns = [d.get(''.join(map(str, x)), ''.join(map(str, x))) for x in df.columns]
我把这个作为一个新问题,因为另一个问题被编辑了很多次
让我们试试:
- 将时间值转换为TimeDelta以获取天数
clip
以确保值不会超过3天- 使用
pivot_table
然后清除列
import numpy as np
import pandas as pd
df = pd.DataFrame({'col1': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A'},
'col2': {0: 'A_1', 1: 'A_2', 2: 'A_1', 3: 'A_1', 4: 'A_1',
5: 'A_2'},
'time': {0: '05:02:03', 1: '15:36:14', 2: '28:21:47',
3: '47:21:17', 4: '32:28:01', 5: '37:27:14'}})
df['days'] = (
pd.to_timedelta(df['time']).dt.days # Get Days from Time Delta
.clip(lower=0, upper=3) # Clip at 3 Days
)
time_cols = ['time < 24', '24 <= time < 48',
'48 <= time < 72', 'time >= 72']
df = (
df.pivot_table(index=['col1', 'col2'],
columns='days',
aggfunc='count',
fill_value=np.nan)
.droplevel(0, 1) # Remove Column Multi Index
.reset_index() # Reset index
.rename_axis(None, axis=1) # Remove Axis Name
.rename(columns={i: v for i, v in enumerate(time_cols)})
)
# Add Missing Columns
df[list(set(time_cols).difference(df.columns))] = np.nan
# Reorder Columns
df = df[['col1', 'col2', *time_cols]]
print(df)
df
:
col1 col2 time < 24 24 <= time < 48 48 <= time < 72 time >= 72
0 A A_1 1 3 NaN NaN
1 A A_2 1 1 NaN NaN