I have a tidy Dataframe (which I'm not sure how to produce from scratch) such as:
signal condition epoch time value
0 A 0 -1100 0.12
1 A 0 -1080 0.09
2 A 0 -1060 0.08
...
With several conditions A,B,C
. I want to get a DataFrame with multiindex, and the values of value
column as values in the new (and only) columns A, B, C
so in the end it looks like:
value A B C
epoch time
0 -1100 0.12 0.23 0.09
-1080 0.09 0.22 0.10
-1060 0.08 0.19 0.06
...
I tried to first put everything except value
into the index with set_index(['condition','epoch','time'])
and then transpose or pivot but can't get it right somehow (transpose gives me hierarchical columns and pivot KeyError) I tried e.g.: df.pivot(('epoch','time'),'condition')
You were on the right track using pivot
which is explicitly designed for such long-to-wide transformations:
# show dummy df
print(df)
signal condition epoch time value
0 0 A 0 -1100 0.12
1 1 A 0 -1080 0.09
2 2 A 0 -1060 0.08
3 0 B 0 -1100 0.42
4 1 B 0 -1080 0.29
5 2 B 0 -1060 0.18
6 0 C 0 -1100 0.32
7 1 C 0 -1080 0.59
8 2 C 0 -1060 0.38
# pivot
pd.pivot_table(df, values="value", columns="condition", index=["epoch", "time"])
condition A B C
epoch time
0 -1100 0.12 0.42 0.32
-1080 0.09 0.29 0.59
-1060 0.08 0.18 0.38
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments