convert a list of lists to a dataframe column

Viewed 45

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?

4 Answers

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

DataFrame constructor

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]

Series constructor

Alternatively, use a Series that you convert to frame:

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

manually reshaping input for the DataFrame constructor

Or manually 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])

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]

Try agg:

>>> df.agg(list, axis=1)
0       [I, have, an, apple]
1    [she, have, an, orange]
dtype: object
>>> 

To a DataFrame:

>>> df.agg(list, axis=1).to_frame('text')
                      text
0     [I, have, an, apple]
1  [she, have, an, orange]
>>> 

Try:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.Series(lst, name='text').apply(lambda x: ', '.join(f"'{a}'" for a in x)).to_frame()

Output:

                            text
0     'I', 'have', 'an', 'apple'
1  'she', 'have', 'an', 'orange'
Related