简体   繁体   English

如何使用python将数据插入csv中的特定单元格?

[英]How to insert data into a specific cell in csv with python?

I am trying to insert data into a specific cell in csv.我正在尝试将数据插入到 csv 中的特定单元格中。 My code is as follows.我的代码如下。

The existing file.现有文件。

在此处输入图像描述

Output输出

The data in cell A1("Custmor") is replaced with new data("Name").单元格 A1("Custmor") 中的数据被替换为新数据("Name")。

在此处输入图像描述

My code is as follows.我的代码如下。

import pandas as pd

#The existing CSV file
file_source = r"C:\Users\user\Desktop\Customer.csv"

#Read the existing CSV file
df = pd.read_csv(file_source)

#Insert"Name"into cell A1 to replace "Customer"
df[1][0]="Name"

#Save the file
df.to_csv(file_source, index=False)

And it doesn't work.它不起作用。 Please help me finding the bug.请帮助我找到错误。

Customer是列标题,你需要做

df = df.rename(columns={'Customer': 'Name'})

I am assuming you are going to want to work with header less csv so if that's the case, your code is already correct, just need to add header=None while reading from csv我假设您将要使用 header less csv 所以如果是这种情况,您的代码已经正确,只需要在从 csv 读取时添加header=None

import pandas as pd

#The existing CSV file
file_source = r"C:\Users\user\Desktop\Customer.csv"

#Read the existing CSV file
df = pd.read_csv(file_source,header=None) #notice this line is now different

#Insert"Name"into cell A1 to replace "Customer"
df[1][0]="Name"

#Save the file
df.to_csv(file_source, index=False,header=None) #made this header less too

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

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