简体   繁体   中英

How do dcast a pandas dataframe and then map the column names when dropping the index

I have the following dataframe

import pandas as pd
       df = pd.DataFrame({'fmc': [1, 2],
                       'id_r': [1, 1],
                       'id_b': ['a', 'b'],
                       'id_c': ['br', 'br'],
                       'fmc_': ['aa_bb', 'cc_dd']})

I would like to dcast this df with index=['id_r', 'id_b', 'id_c'] and values='fmc' .

I would like the output to be like

import numpy as np
        dff = pd.DataFrame({'id_r': [1, 1],
                      'id_b': ['a', 'b'],
                      'id_c': ['br', 'br'],
                      'fmc_aa_bb':[1, np.nan],
                      'fmc_cc_dd':[np.nan, 2]})

I followed a previous question of mine

  df = df.pivot_table(index=['id_r', 'id_b', 'id_c'], columns='fmc_', values='fmc')
        df.columns = df.columns.map('_'.join)
        df = df.reset_index()

But does not give the desired output.

Any help?

Modify your code with add_prefix

s=df.pivot_table(index=['id_r', 'id_b', 'id_c'], columns='fmc_', values='fmc').add_prefix('fmc_').reset_index()
Out[190]: 
fmc_  id_r id_b id_c  fmc_aa_bb  fmc_cc_dd
0        1    a   br        1.0        NaN
1        1    b   br        NaN        2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM