Search code examples
pythonpandascalculated-columns

Get column name as new column with the same column value


I have dataframe similar to this one:


name    hobby   date         country      5           10           15         20 ...
Toby    Guitar  2020-01-19    Brazil     0.1245       0.2543      0.7763     0.2264
Linda   Cooking 2020-03-05    Italy      0.5411       0.2213      Nan        0.3342
Ben     Diving  2020-04-02    USA        0.8843       0.2333      0.4486     0.2122
...

I want to the the int colmns, duplicate them, and put the int as the new value of the column, something like this:


name    hobby   date         country      5      5     10      10     15     15    20      20...
Toby    Guitar  2020-01-19    Brazil     0.1245  5     0.2543  10    0.7763  15   0.2264   20
Linda   Cooking 2020-03-05    Italy      0.5411  5     0.2213  10    Nan     15   0.3342   20
Ben     Diving  2020-04-02    USA        0.8843  5     0.2333  10    0.4486  15   0.2122   20
...

I'm not sure how to tackle this and looking for ideas


Solution

  • Here is a solution you can try out,

    digits_ = pd.DataFrame(
        {col: [int(col)] * len(df) for col in df.columns if col.isdigit()}
    )
    
    pd.concat([df, digits_], axis=1)
    

        name    hobby        date country       5  ...      20  5  10  15  20
    0   Toby   Guitar  2020-01-19  Brazil  0.1245  ...  0.2264  5  10  15  20
    1  Linda  Cooking  2020-03-05   Italy  0.5411  ...  0.3342  5  10  15  20
    2    Ben   Diving  2020-04-02     USA  0.8843  ...  0.2122  5  10  15  20