Issue
I'm seeking advice on populating a dataframe in pandas. I've now created a dataframe that looks like A:
However, eventually, it should looks like something in B, hopefully:
Could anyone suggest how to create a dataframe like B on top of A, if I have relevant data values.
Any comments or suggestions are highly appreciated.
Solution
I assume you have two dataframes that look like A. One for feature F1 and one for F2.
Then you create B like this:
a1 = ... # assuming A1, A2 already have correct index A, B, C as depicted.
a2 = ...
a1['Features'] = "F1"
a2['Features'] = "F2"
b = (pd.concat([a1, a2], axis=0)
.set_index("Features", append=True)
# Swing the new index level - Features - around to become a column level instead.
.unstack("Features"))
You've named the column level "Features" but I'd suggest using "Feature" instead, if you can.
There is also an alternate way to do the same thing, also seen in this question: How to make dataframe behave such as pandas_datareader
(pd.concat([a1, b2], axis='columns', keys=pd.Index(["F1", "F2"], name="Features"))
# swap hierarchy order of column levels
.swaplevel(-2, -1, axis=1)
# restore sorting to that of a1 columns - assuming a1, a2 have the same cols
.reindex(columns=a1.columns, level=0)
)
Answered By - creanion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.