1

i have a csv file with the following data as follows: input

i want to convert the columns into rows: output

I have tried the following code:

mydict = dict(zip(df.title, df.score))
    # s = pd.Series(list(mydict.items()))
    # df_final = pd.DataFrame(s)

and write the ouput to a new csv file. How can i do that?

2 Answers2

0

Use:

df = pd.DataFrame({'title':['p1','p2','p3'],
                   'score':[1,0.1,2]})
print (df)
  title  score
0    p1    1.0
1    p2    0.1
2    p3    2.0

df1 = pd.DataFrame([df.score.values], columns=df.title.values)

Alternative:

df1 = df.set_index('title')['score'].to_frame(0).T.rename_axis(None, 1)

print (df1)
    p1   p2   p3
0  1.0  0.1  2.0

df.to_csv(file, index=False)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Very small solution

import pandas as pd
df =  pd.read_csv("inputfile")
print df.set_index('title').T

Original df:

  cluster       budget
0       a  4133.333333
1       b   300.000000
2       c   575.000000

Output of above code:

cluster            a      b      c
budget   4133.333333  300.0  575.0
LOrD_ARaGOrN
  • 3,884
  • 3
  • 27
  • 49