我有以下 pandas 数据框:
Date Variable
2018-04-10 21:05:00 a
2018-04-10 21:05:00 a
2018-04-10 21:10:00 b
2018-04-10 21:15:00 a
2018-04-10 21:35:00 b
2018-04-10 21:45:00 a
2018-04-10 21:45:00 a
我的目标是计算包含 'a'
的行数,这些行数在 30 分钟之前和 30 分钟之前
每次之后的分钟数(包括前后时间相同的行)
之后,但不包括正在分析的每一行)。然后对每个做同样的事情
变量
。因此,对于 Variable
a
我最终会得到如下所示的结果:
Date nr_30_min_bef_a nr_30_min_after_a
2018-04-10 21:05:00 1 2
2018-04-10 21:05:00 1 2
2018-04-10 21:10:00 2 1
2018-04-10 21:15:00 2 2
2018-04-10 21:35:00 3 2
2018-04-10 21:45:00 2 1
2018-04-10 21:45:00 2 1
我尝试执行 for 循环来迭代所有行,问题是 整个系列有超过一百万行,因此我一直在寻找更多 有效的解决方案。
import pandas as pd
df = pd.DataFrame({'Date': ['2018-04-10 21:05:00',
'2018-04-10 21:05:00',
'2018-04-10 21:10:00',
'2018-04-10 21:15:00',
'2018-04-10 21:35:00',
'2018-04-10 21:45:00',
'2018-04-10 21:45:00'],
'Variable': ['a', 'a', 'b', 'a', 'b', 'a', 'a']})
提前致谢。
最佳答案
以此为基础 previous answer , 你可以使用
import pandas as pd
df = pd.DataFrame({'Date': ['2018-04-10 21:05:00',
'2018-04-10 21:05:00',
'2018-04-10 21:10:00',
'2018-04-10 21:15:00',
'2018-04-10 21:35:00',
'2018-04-10 21:45:00',
'2018-04-10 21:45:00'],
'Variable': ['a', 'a', 'b', 'a', 'b', 'a', 'a']})
df['Date'] = pd.to_datetime(df['Date'])
freq_table = pd.crosstab(index=df['Date'], columns=df['Variable'])
df_bef = freq_table.rolling('30T', closed='both').sum().astype(int)
is_current = (freq_table != 0).astype(int)
df_bef -= is_current
df_bef.columns = ['nr_30_min_bef_{}'.format(col) for col in df_bef.columns]
result = pd.merge(df, df_bef, left_on='Date', right_index=True)
max_date = df['Date'].max()
min_date = df['Date'].min()
pseudo_dates = (max_date - df['Date'])[::-1] + min_date
freq_table_reversed = pd.crosstab(index=pseudo_dates, columns=df['Variable'])
df_after = freq_table_reversed.rolling('30T', closed='both').sum().astype(int)
df_after = pd.DataFrame(df_after.values[::-1], index=freq_table.index,
columns=df_after.columns)
df_after -= is_current
df_after.columns = ['nr_30_min_after_{}'.format(col) for col in df_after.columns]
result = pd.merge(result, df_after, left_on='Date', right_index=True)
print(result)
打印内容
Date Variable nr_30_min_bef_a nr_30_min_bef_b nr_30_min_after_a nr_30_min_after_b
0 2018-04-10 21:05:00 a 1 0 2 2
1 2018-04-10 21:05:00 a 1 0 2 2
2 2018-04-10 21:10:00 b 2 0 1 1
3 2018-04-10 21:15:00 a 2 1 2 1
4 2018-04-10 21:35:00 b 3 1 2 0
5 2018-04-10 21:45:00 a 2 1 1 0
6 2018-04-10 21:45:00 a 2 1 1 0
<小时/>
主要的新想法是使用pd.crosstab
生成频数表:
freq_table = pd.crosstab(index=df['Date'], columns=df['Variable'])
# Variable a b
# Date
# 2018-04-10 21:05:00 2 0
# 2018-04-10 21:10:00 0 1
# 2018-04-10 21:15:00 1 0
# 2018-04-10 21:35:00 0 1
# 2018-04-10 21:45:00 2 0
然后将每个滚动窗口中的数字相加:
df_bef = freq_table.rolling('30T', closed='both').sum().astype(int)
由于您希望从计数中排除当前行,因此从 df_bef
中减去 is_current
:
is_current = (freq_table != 0).astype(int)
df_bef -= is_current
关于Python - 基于 100 万行表上的日期差异的向量化条件变量总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50786484/