I have the following DataFrame:
Country NumberA
0 France 25
1 China 30
2 US 15
My goal Is to convert it to the following frame:
NewDf = pd.DataFrame({'France': [25],
'China': [30],
'US': [15]},
index=[0])
To do so I tried to define a function:
def Convert(df):
for i in range(len(df)):
NewDf = pd.DataFrame({df[df.columns[0]].iloc[i]: df[df.columns[1]].iloc[i]},
index=[0])
return NewDf
But when I print it:
print(Convert(MyTestDataFrame))
It return only the last row:
US
0 15
What am I doing wrong there ?
Instead of:
France China US
0 25 30 15
CodePudding user response:
try this:
df.set_index('Country').T
It should give you the expected result.
If you really need to have 0 as index, add .reset_index(drop=True)
CodePudding user response:
from what i understand this would be the solution you need.
import pandas as pd
NewDf = pd.DataFrame({'Country': ['France','China','US'],
'NumberA': [25,30,15]})
col = NewDf['Country'].values.tolist()
row = NewDf['NumberA'].values.tolist()
data = {}
for x in range(0, len(col)):
data[col[x]] = [row[x]]
NewDf2 = pd.DataFrame(data)
print("FIRST DATAFRAME:\n" str(NewDf) "\n\nSECOND DATAFRAME:\n" str(NewDf2))