[英]How can a Pandas Data frame with datetime index be grouped by date in a way that values belonging to the date are split into multiple columns?
Consider a dataframe:考虑一个数据框:
timestamp value
0 2019-07-12 18:00:00 8.46
1 2019-07-13 06:00:00 12.02
2 2019-07-13 18:00:00 15.58
3 2019-07-14 06:00:00 16.29
4 2019-07-14 18:00:00 17.00
I want to transform in to:我想转变为:
timestamp X1 X2
0 2019-07-12 8.46 NaN
1 2019-07-13 12.02 15.58
2 2019-07-14 16.29 17.00
How can this be done?如何才能做到这一点?
I tried pd.groupby
with Grouper
and then doing a for loop like below:我用
Grouper
尝试了pd.groupby
,然后执行如下 for 循环:
for ix, i in resampled_df.groupby(pd.Grouper(key='timestamp', freq="1D")):
print(i.head())
No luck!没有运气!
Let's try with pivot_table
:让我们尝试使用
pivot_table
:
# Convert to datetime (if not already)
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Get Series of Dates from Timestamp
dates = df['timestamp'].dt.date
df = (
# Pivot on dates in index, and columns based on rows per group
df.pivot_table(index=dates,
columns=df['value'].groupby(dates).cumcount() + 1,
values='value')
.add_prefix('X') # Add X in Front of Columns
.reset_index() # Make dates a column
)
df
: df
:
timestamp X1 X2
0 2019-07-12 8.46 NaN
1 2019-07-13 12.02 15.58
2 2019-07-14 16.29 17.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.