Home > OS >  Transpose and save a one column pandas dataframe
Transpose and save a one column pandas dataframe

Time:11-05

I removed all except one row of a pandas dataframe and pandas automatically transposed it. I then try to retranspose it back (and eventually want save it as a .csv) without effect.

As a final result I want to have:

df3:
col1  col2  col3  
2     7     5

instead of

df3:
col1    2
col2    7
col3    5

and in the save .csv I want to have:

,col1,col2,col3
1,2,7,5
,1
col1,2
col2,7
col3,5

Here is the script:

import pandas as pd
d1 = {
    'col1': [1, 2], 
    'col2': [4, 7], 
    'col3': [8, 5], 
    }
df1 = pd.DataFrame(data=d1)
df2 = df1.loc[df1.loc[:,"col2"].idxmax(),:]
df3 = df2.transpose() # df2.That
print(df1)
print(df2)
print("df3:")
print(df3)
df3.to_csv("df3.csv")

CodePudding user response:

In your case do to_frame

df3.to_frame().T

CodePudding user response:

You can use:

df1[df1.index == df1['col2'].idxmax()]

or to keep your logic:

df1.loc[df1['col2'].idxmax()].to_frame().T

output:

   col1  col2  col3
1     2     7     5
  • Related