I have a dictionary with four keys pointing to one array each:
import pandas as pd
import csv
complete = {'average': ['a1', 'a2', 'a3', 'a4'], 'hard': ['h1', 'h2', 'h3', 'h4','h5'], 'easy': ['e1', 'e2', 'e3', 'e4','e5','e6'], 'difficult': ['d1', 'd2', 'd3', 'd4','d5','d6','d7']}
df = pd.DataFrame(complete,orient='index').to_csv('out.csv')
df.transpose()
How can I write this dictionary to a csv file where the keys represent one column header, while arrays will fill the corresponding column underneath.
average | hard | easy | difficult |
a1 | h1 | e1 | d1 |
a2 | h2 | e2 | d2 |
a3 | h3 | e3 | d3 |
a4 | h4 | e4 | d4 |
| h5 | e5 | d5 |
| e6 | d6 |
| d7 |
As you can tell, I have tried using both the pandas and the csv library. Not sure what I am doing wrong, but this code produce the following output:
TypeError: __init__() got an unexpected keyword argument 'orient'
Your command
df = pd.DataFrame(complete,orient='index').to_csv('out.csv')
is missing from_dict:
df = pd.DataFrame.from_dict(complete, orient='index').transpose()
df.to_csv('out.csv')
See also here
You could create a list of DataFrames one for each key, value pair in the dictionary complete, then use pd.concat:
import pandas as pd
complete = {'average': ['a1', 'a2', 'a3', 'a4'],
'hard': ['h1', 'h2', 'h3', 'h4', 'h5'],
'easy': ['e1', 'e2', 'e3', 'e4', 'e5', 'e6'],
'difficult': ['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7']}
df = [pd.DataFrame({ k : v }) for k, v in complete.items()]
df = pd.concat(df, axis=1)
print(df)
Output
average hard easy difficult
0 a1 h1 e1 d1
1 a2 h2 e2 d2
2 a3 h3 e3 d3
3 a4 h4 e4 d4
4 NaN h5 e5 d5
5 NaN NaN e6 d6
6 NaN NaN NaN d7
The DataFrame can be saved to a csv file by doing:
df.to_csv('output.csv', index=False)
see the documentation on to_csv here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With