简体   繁体   English

如何手动输入 append 到 pandas csv 文件?

[英]How to append to pandas csv file with manual input?

Code代码

import pandas as pd
import csv

my_dict = { 'Customer'    : [],
            'Product'     : []
            }

x = input("Customer:")
y = input("Product:")

my_dict['Customer'].append(x)
my_dict['Product'].append(y)



df = pd.DataFrame(my_dict)


df.to_csv('data.csv', encoding='utf-8', index= True)

Output Output

,Customer,Product
0,Customer 1,Product 1

Question问题

How can I append new row If I run the script again and input new values?如果我再次运行脚本并输入新值,我该如何 append 新行?

Example例子

If I run the script again and my input would be Customer 2 & Product 2 and add new index too.如果我再次运行脚本,我的输入将是Customer 2 & Product 2并添加新index I want the output to look like this in csv file:我希望 output 在 csv 文件中看起来像这样:

,Customer,Product
0,Customer 1,Product 1
1, Customer 2, Product 2

But at the moment, it is just overwriting it.但目前,它只是覆盖它。

You want to append the data to the existing data so try to read in the file and append the data:您想将 append 数据转换为现有数据,因此尝试读取文件和 append 数据:

import pandas as pd
import csv

try: #tries to read in existing data.csv file
    df = pd.read_csv('data.csv', encoding='utf-8', index_col = 0)
except FileNotFoundError: #if no file exists yet, create an empty dataframe
    df = pd.DataFrame()


my_dict = { 'Customer'    : [],
            'Product'     : []
            }

x = input("Customer:")
y = input("Product:")

my_dict['Customer'].append(x)
my_dict['Product'].append(y)



df = df.append(pd.DataFrame(my_dict))


df.to_csv('data.csv', encoding='utf-8', index= True)

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

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