Home > Blockchain >  Obtain a pandas dataframe with two columns from a python list
Obtain a pandas dataframe with two columns from a python list

Time:01-18

I have a list like

list1=['wwe', '0.99,', 'aew', '0.80,', 'ufc', '1,', 'tna', '0.45,', 'wwf', '1,', 'ring of honor', '0.6,']

I am trying to push the list in a pandas dataframe such that my dataframe looks like this:

shows          ratings
wwe            0.99
aew            0.80
ufc            1
tna            0.45
wwf            1
ring of honor  0.6

I tried different ways to get this dataframe but fail to get it, how do I achieve this?

CodePudding user response:

Use DataFrame constructor with reshape, here -1 is count by numpy and then remove comma with converting to floats for column ratings:

df = pd.DataFrame(np.reshape(list1, (-1,2)), columns=['shows','ratings'])

df['ratings'] = df['ratings'].str.strip(',').astype(float)
print (df)
           shows  ratings
0            wwe     0.99
1            aew     0.80
2            ufc     1.00
3            tna     0.45
4            wwf     1.00
5  ring of honor     0.60

CodePudding user response:

import pandas as pd
list1=['wwe', '0.99,', 'aew', '0.80,', 'ufc', '1,', 'tna', '0.45,', 'wwf', '1,', 'ring of honor', '0.6,']


col1 = list1[::2]
col2 = list1[1::2]

# create dataframe from col1 and col2 
df = pd.DataFrame({'shows':col1, 'ratings':col2})

  •  Tags:  
  • Related