Search code examples
pythonpandasdataframepivot

How to get the correct pivoting for a pandas dataframe?


I have following pandas DataFrame:

import pandas as pd
df2 = pd.DataFrame({
    'nombreNumeroUnico': ['UP2_G1_B', 'UP2_G2_B'],
    'pMax': [110.0, 110.0]
})

df2
((Out  [1])): 
  nombreNumeroUnico   pMax
0          UP2_G1_B  110.0
1          UP2_G2_B  110.0

Expected result

I want to transform this into:

   UP2_G1_B  UP2_G2_B
0       110       110

What I have tried so far

So far I was able to convert it using pivot function but I am not getting the exact result I want.

df2.pivot(index=None, columns="nombreNumeroUnico", values="pMax")
((Out  [57])): 
nombreNumeroUnico  UP2_G1_B  UP2_G2_B
0                     110.0       NaN
1                       NaN     110.0

Question

But it's not the exact result I want. How can I get the expected result?


Solution

  • Pls use df2.set_index('nombreNumeroUnico').T.reset_index(drop=True)

    Test Code:

    import pandas as pd
    
    df2 = pd.DataFrame({
        'nombreNumeroUnico': ['UP2_G1_B', 'UP2_G2_B'],
        'pMax': [110.0, 110.0]
    })
    
    result_df = df2.set_index('nombreNumeroUnico').T.reset_index(drop=True)
    result_df.columns.name = None
    print(result_df)
    

    Output:

       UP2_G1_B  UP2_G2_B
    0     110.0     110.0