Python将时间戳字符串数据重新采样为每周数据



我在每个时间戳生成字符串数据。我想把它转换成每周的数据。我的代码:

df = 
index                   data
2019-10-01 08:43:54    A
2019-10-01 08:45:24    B
2019-10-02 08:49:42    C
2019-10-02 09:01:04    A
2019-10-03 09:07:04    A
2019-10-10 08:43:54    A
2019-10-10 08:45:24    B
2019-10-12 08:49:42    C
2019-10-12 09:01:04    B
2019-10-13 09:07:04    A

目标:将上述数据转换为每周数据。每周平均数据应包括特定字符串重复的次数所需答案

wdf =                              # Weekly dataframe
index          A    B   C
2019-10-01     3    1   1
2019-10-08     2    2   1

我有两个问题:Q1.我下面描述的解决方案是最好的方法吗?Q2.有更好的解决方案吗?

我的方法:在原始数据帧中创建额外的列,如果"数据"列中存在字符串,则分配1或0

new_cols = df['data'].unique().tolist()
df[new_cols] = " "
df[new_cols] = df[new_cols].isin() # I think this is not the right code. 
df =             # This is expected solution from above code
index                   data    A     B     C
2019-10-01 08:43:54    A        1     0     0
2019-10-01 08:45:24    B        0     1     0
2019-10-02 08:49:42    C        0     0     1
2019-10-02 09:01:04    A        1     0     0
2019-10-03 09:07:04    A        1     0     0
2019-10-10 08:43:54    A        1     0     0
2019-10-10 08:45:24    B        0     1     0
2019-10-12 08:49:42    C        0     0     1
2019-10-12 09:01:04    B        0     1     0
2019-10-13 09:07:04    A        1     0     0
wdf = df[new_cols]
wdf['datetime'] = wdf.index
wdf = wdf.resamle('W',on='datetime').sum()
wdf =                              # Weekly dataframe
index          A    B   C
2019-10-01     3    1   1
2019-10-08     2    2   1
一种方法是使用pd.pivot_table。假设您有这个带有日期时间索引的数据帧:
data
index                   
2019-10-01 08:43:54    A
2019-10-01 08:45:24    B
2019-10-02 08:49:42    C
2019-10-02 09:01:04    A
2019-10-03 09:07:04    A
2019-10-10 08:43:54    A
2019-10-10 08:45:24    B
2019-10-12 08:49:42    C
2019-10-12 09:01:04    B
2019-10-13 09:07:04    A

然后:

print(
df.pivot_table(
index=pd.Grouper(freq="7D"),
columns="data",
aggfunc="size",
)
)

打印:

data        A  B  C
index              
2019-10-01  3  1  1
2019-10-08  2  2  1

如果"index"只是普通列:

print(
df.pivot_table(
index=pd.Grouper(key="index", freq="7D"),
columns="data",
aggfunc="size",
)
)

考虑将index作为列名
(如果没有,则重置索引,df = df.reset_index()(

df['index'] = pd.to_datetime(df['index'])
df.groupby(['data', pd.Grouper(key='index', 
freq='W')]).data.count().unstack(-2)

输出

data    A   B   C
index           
2019-10-06  3   1   1
2019-10-13  2   2   1

如果我们不需要多索引:

df.groupby(['data', pd.Grouper(key='index', 
freq='W')]).data.count().unstack(-2).rename_axis(None,axis="columns").reset_index()

输出

index       A   B   C
0   2019-10-06  3   1   1
1   2019-10-13  2   2   1

最新更新