Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split multiple columns in dataframe paired with specific column

Tags:

python

pandas

I have a dataframe as follows df:

Var_1       Var_2       Var_3     …    Var_n     date                                     
0.016008    0.040933    0.121261  ...  146989.0  2018-03-21
0.015507    0.042487    0.116209  ...  144053.0  2018-03-22
0.015420    0.048447    0.125908  ...  154255.0  2018-03-23
0.014087    0.108278    0.115745  ...  167322.0  2018-03-24
0.016481    0.041167    0.078635  ...  210130.0  2018-03-25

I want to subset pairs of Var_i and date columns then return renamed dataframes with corresponding Var_i:

names_df = df.columns.to_list()
for i in names_df:
    i = df.loc[:, ['date', i]]  # or something like df_Var_i = ...

But, apparently such code does not work. I was wondering if there is a simple way to handle it.

like image 417
maaniB Avatar asked Jul 30 '26 09:07

maaniB


1 Answers

You could melt, then groupby the variable column, containing all melted date columns, and create a dictionary (or list) from the groupby object:

d = dict(tuple(df.melt(id_vars='date').groupby('variable')))

d.keys()
dict_keys(['Var_1', 'Var_2', 'Var_3', 'Var_n'])

d['Var_1'].drop('variable',1)
         date     value
0  2018-03-21  0.016008
1  2018-03-22  0.015507
2  2018-03-23  0.015420
3  2018-03-24  0.014087
4  2018-03-25  0.016481
like image 158
yatu Avatar answered Aug 01 '26 21:08

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!