![](/img/trans.png)
[英]Pandas, how to replace mean values in python data frame using multiple grouped columns
[英]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?
考慮一個數據框:
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
我想轉變為:
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
如何才能做到這一點?
我用Grouper
嘗試了pd.groupby
,然后執行如下 for 循環:
for ix, i in resampled_df.groupby(pd.Grouper(key='timestamp', freq="1D")):
print(i.head())
沒有運氣!
讓我們嘗試使用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
:
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.