python - Split Multilevel dataframe into different csv files -
suppose have following dataframe :
x y ---+---+---+--- | b | | b --+---+---+---+--- 0 | 1 | 2 | 3 | 4 1 | 5 | 6 | 7 | 8 2 | 9 | 10| 11| 12
i want split based on multilevel index recursively , save them in csv file.
for example file name x_a.csv should contain following dataframe:
x --- --+--- 0 | 1 1 | 5 2 | 9
similarly file x_b.csv should store dataframe :
x --- b --+--- 0 | 2 1 | 6 2 | 10
and on y_a , y_b.
i looking pythonic ( or efficient) way rather iterating on column values separately code quite large. tried using techniques mentioned here dropping column levels , storing individual columns want in such way don't have explicitly mention column names since dataframe may expand ( i.e. @ top level there might 4 columns w, x, y , z).
list_of_df = [df[i].to_frame() in df.columns]
with @johngalt's suggestion csv:
_ = [df[i].to_frame().to_csv('{0}_{1}'.format(*i)) in df.columns]
output:
list_of_df[0]
x 0 1 1 5 2 9
list_of_df[1]
x b 0 2 1 6 2 10
...
list_of_df[3]
y b 0 4 1 8 2 12
Comments
Post a Comment