简体   繁体   English

Python 将字典转换为 dataframe 并将其导出到 csv 文件

[英]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.我正在尝试将字典转换为 dataframe,然后将其导出到 csv 文件,但由于某种原因,当程序导出 dataframe 时,它会更改列和行。

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:我想要的 output:

name,balance
xyzz,0 
abc,0

the output I get: output 我得到:

name,xyzz,abcd   
balance,0,0

The issue you are facing is names and balances have different lengths.您面临的问题是namesbalances有不同的长度。 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.当您调用acc_creation(name)时,您向namesnames.append(name) )添加了一个额外的元素,但没有添加到balance ,因此存在长度不匹配。 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.如果您收到该错误消息,请让我们查看一些原始 csv,以便我们对其进行测试并了解原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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