Home > Blockchain >  convert a list of lists to a dataframe column
convert a list of lists to a dataframe column

Time:10-14

I have a list looks like this:

mylist = [['I','have','an','apple'],['she','have','an','orange']]

and I want each list contained in mylist should be a row in the dataframe and the dataframe should look like this:

          text
'I','have','an','apple'
'she','have','an','orange'

I tried to convert it but it shows a results like this:

 0        1      2       3
'I'    'have'   'an'  'apple'
'she'  'have'   'an'  'orange'

How should I do it?

CodePudding user response:

You can use pd.DataFrame([mylist]).T.

CodePudding user response:

Here is a super simple way to do this by only using pd.DataFrame -

mylist = [['I','have','an','apple'],['she','have','an','orange']]

df = pd.DataFrame({'text':mylist})
print(df)
                      text
0     [I, have, an, apple]
1  [she, have, an, orange]

CodePudding user response:

Try agg:

df.agg(list, axis=1)

CodePudding user response:

You can use a dictionary in the DataFrame constructor:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.DataFrame({'name': lst})

output:

                      name
0     [I, have, an, apple]
1  [she, have, an, orange]

Alternatively, use a Series that you convert to frame:

df = pd.Series(lst, name='text').to_frame()

NB. do not use list as a variable, this overwrites the python builtin

older version:

You can wrap each list in a sublist to avoid expansion to columns:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.DataFrame([[e] for e in lst])
  • Related