Excuse me. I am a noob I saw Python import csv to list Pandas #2
if I have this csv
JavaScript
x
8
1
country population population_time EUR
2
Germany 82521653.0 2016-12-01 True
3
France 66991000.0 2017-01-01 True
4
Indonesia 255461700.0 2017-01-01 False
5
Ireland 4761865.0 NaT True
6
Spain 46549045.0 2017-06-01 True
7
Vatican NaN NaT True
8
How to change like this
JavaScript
1
7
1
[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-0100:00:00'), 'EUR': True},
2
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
3
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
4
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
5
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
6
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]
7
I just can do like this
JavaScript
1
4
1
import pandas as pd
2
df = pd.read_csv('file.csv')
3
print(df.to_dict())
4
result:
JavaScript
1
5
1
{'country':{0:'Germany', 1:'France', 2:'Indonesia', 3:'Ireland', 4:'Spain', 5:'Vatican'},
2
'population ':{0:'82521653.0', 1:'66991000.0', 2:'255461700.0', 3:'4761865.0', 4:'46549045.0', 5:'NaN'},
3
'population_time':{0:'2016-12-01', 1:'2017-01-01', 2:'2017-01-01', 3:'NaT', 4:'2017-06-01', 5:'NaT'},
4
'EUR':{0:'True', 1:'True', 2:'False', 3:'True', 4:'True', 5:'True'},
5
Advertisement
Answer
Almost there. Little change to your code. Notice the keyword argument ‘orient’.
JavaScript
1
4
1
import pandas as pd
2
df = pd.read_csv('file.csv')
3
print(df.to_dict(orient='records'))
4
It gives the following output
JavaScript
1
2
1
[{'country': 'Germany', 'population': 82521653.0, 'opulation_time': '2016-12-01', 'EUR': True}, {'country': 'France', 'population': 66991000.0, 'opulation_time': '2017-01-01', 'EUR': True}, {'country': 'Indonesia', 'population': 255461700.0, 'opulation_time': ' 2017-01-01', 'EUR': False}, {'country': 'Ireland', 'population': 4761865.0, 'opulation_time': 'NaT', 'EUR': True}, {'country': 'Spain', 'population': 46549045.0, 'opulation_time': '2017-06-01', 'EUR': True}, {'country': 'Vatican', 'population': nan, 'opulation_time': 'NaT', 'EUR': True}]
2