简体   繁体   中英

Python converting dictionary to dataframe and exporting it to a csv file

I am trying to convert a dictionary to a dataframe and then exporting it to a csv file but for some reason when the program exports the dataframe it changes the columns and rows.

df = pd.read_csv('test.csv')
for i in range(len(df['name'])):
    names.append(df['name'][i])
    balances.append(df['balance'][i])





def acc_creation(name):
    names.append(name)
    dict = {'name': names, 'balance': balances}
    new_df = pd.DataFrame.from_dict(
        dict, orient='index', columns=['name', 'balance'])
    new_df.to_csv('test.csv', encoding='utf-8', sep=',',
                  header=False, na_rep=0, index=True)

then it stops working and this is the error i get:

Traceback (most recent call last):
  File "/Users/darkmbs/Desktop/python/test.py", line 9, in <module>
    balances.append(df['balance'][i])
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/frame.py", line 3024, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 'balance'

the output I want:

name,balance
xyzz,0 
abc,0

the output I get:

name,xyzz,abcd   
balance,0,0

The issue you are facing is names and balances have different lengths. When you call acc_creation(name) you add an extra element to names ( names.append(name) ), but not to balance , so there is a length mismatch. Something you could do is:

import pandas as pd
import numpy as np

def acc_creation(name):
    names.append(name)
    balances.append(0) # Or any value
    new_df = pd.DataFrame(np.column_stack([names, balances]), 
                                   columns=['name', 'balance'])
    new_df.to_csv('test.csv', encoding='utf-8', sep=',',
                  header=True, na_rep=0, index=True)

I believe you just remove:

 orient='index',

If you are getting that error message, let us see some of the original csv so we can test it and understand why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM