Home > Mobile >  Is there a way to take all of my row values and make them col headers?
Is there a way to take all of my row values and make them col headers?

Time:08-02

I currently have a long list of countries (234 values). For simplicity sake, picture enter image description here

CodePudding user response:

7Shoe's answer is good, but in case you already have a dataframe:

import pandas as pd 

df = pd.DataFrame({'Country':['U.S.','Canada', 'India']})
pd.DataFrame(columns=df.Country, index=df.Country).rename_axis(None)

Output

Country U.S. Canada India
U.S.     NaN    NaN   NaN
Canada   NaN    NaN   NaN
India    NaN    NaN   NaN

CodePudding user response:

Will something like this work?

data = ["US","China","England","Spain",'Brazil']
df = pd.DataFrame({"Country":data})
df[df.Country.values] = ''
df

Output:


   Country  US  China   England Spain   Brazil
0   US                  
1   China                   
2   England                 
3   Spain                   
4   Brazil                                  

You can even set the country as the index like:

data = [1,2,3,4,5]
df = pd.DataFrame({"Country":data})
df[df.Country.values] = ''
df = df.set_index(df.Country)[df.Country.values].rename_axis(index=None)

Output:


        US  China   England Spain   Brazil
US                  
China                   
England                 
Spain                   
Brazil                                  
  • Related