Pandas不会将新的 Dataframe 连接到csv文件

kt06eoxx  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(106)

我试图使一个程序,我有一个已经存在的csv文件,我寻求能够添加数据多次。然而,即使我没有得到任何错误消息,我没有得到额外的数据更新的文件。
代码如下:

import pandas as pd 
import numpy as np 
import csv 
from faker import Faker`your text`
import random

fake = Faker()

with open('recources2.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["Name", "Attack", "Defence", "Consumption"])
        writer.writerow([fake.name(), 20, 12, 7])
        file.close()


def soldierGeneration(x):

    for i in range (0,x):
        attackValue = random.randint(0,21)
        defenceValue = random.randint(0,21)
        consumptionValue = random.randint(0,11)
        df = pd.read_csv('recources2.csv')
        Soldier = pd.DataFrame([fake.name(), attackValue, defenceValue, consumptionValue])
        pd.concat([df, Soldier], ignore_index=True)
        
        
soldierGeneration(4)

我尝试将整个concat行改为一个单独的变量:

hf = pd.concat([df, Soldier], ignore_index=True) 
print(hf)

由此我得到了另一个输出,这也不是我想要的方式,甚至输出本身看起来真的很奇怪:

Name  Attack  Defence  Consumption             0
0  Kevin Gutierrez    20.0     12.0          7.0           NaN
1              NaN     NaN      NaN          NaN  Thomas Adams
2              NaN     NaN      NaN          NaN             8
3              NaN     NaN      NaN          NaN             4
4              NaN     NaN      NaN          NaN             3
k5ifujac

k5ifujac1#

该问题是由于Soldier的格式不正确(一个长列,而不是具有正确标题的单行)。
你应该改变:

Soldier = pd.DataFrame([fake.name(), attackValue, defenceValue, consumptionValue])

收件人:

Soldier = pd.DataFrame([[fake.name(), attackValue, defenceValue, consumptionValue]],
                       columns=['Name', 'Attack', 'Defence', 'Consumption'])

或者:

Soldier = pd.DataFrame({'Name': [fake.name()],
                        'Attack': [attackValue],
                        'Defense': [defenceValue],
                        'Consumption': [consumptionValue]})

相关问题