Home > Back-end >  Dataframe to CSV with cell value as list
Dataframe to CSV with cell value as list

Time:08-01

I have a pandas dataframe as so

data = {'name': ['alice', 'bob'], 'lucky_numbers': [[1, 2], [3, 4]]}
pd.DataFrame.from_dict(data)

Is there a way to covert this dict to a csv like so,

name,lucky_numbers
alice,1
,2
bob,3
,4

CodePudding user response:

import pandas as pd
data = {'name': ['alice', 'bob'], 'lucky_numbers': [[1, 2], [3, 4]]}
pd.DataFrame.from_dict(data).explode('lucky_numbers').to_csv('lucky_numbers.csv', index=False)

or, if you want exactly that:

import pandas as pd
data = {'name': ['alice', 'bob'], 'lucky_numbers': [[1, 2], [3, 4]]}
df = pd.DataFrame.from_dict(data).explode('lucky_numbers').reset_index(drop=True)
df.loc[~df.index.isin(df.groupby('name').head(1).index), 'name'] = ""
df.to_csv("lucky_numbers.csv", index=False)

CodePudding user response:

If you want to save the luck_numbers as a list will be as simples as data:

import pandas as pd

data = {'name': ['alice', 'bob'], 'lucky_numbers': [[1, 2], [3, 4]]}
df = pd.DataFrame.from_dict(data)
df.to_csv('your_file_name.csv', sep=',', index=False)

Output

name,lucky_numbers
alice,"[1, 2]"
bob,"[3, 4]"
  • Related