[英]How to write in an existing CSV file with data from another csv file?
Just a bit of context: I have two CSV files:只是一点上下文:我有两个 CSV 文件:
The first one which I will call the Statement第一个我称之为声明
The second one the Big File第二个大文件
The Big File contains a lot of data including Order ID
numbers that are in the Statement .大文件包含大量数据,包括Statement中的Order ID
号。
What I want to do is:我想做的是:
If the Order ID
from the Statement matches the Order ID
from the Big File , then write in Big File in the column Paid
, at the row that contains the Order ID
, "Yes"
.如果Order ID
从声明的匹配Order ID
从大文件,然后写在列大文件Paid
,在包含该行Order ID
, "Yes"
。
So what I wrote was:所以我写的是:
import pandas as pd
data1 = pd.read_csv('Big_File.csv')
data2 = pd.read_csv('Statement.csv')
df = pd.DataFrame(data1)
for i in range(len(data1['PO'])):
for j in range(len(data2['PO'])):
if data2['PO'][j] == data1['PO'][i]:
data1['Supplier'][i] = 'SUP'
data1['Paid'][i] = 'yes'
When I run the code, no error, but then I open the Big File to check if it worked and nothing changed.当我运行代码时,没有错误,但是我打开大文件检查它是否有效并且没有任何改变。
I am new to writing and reading files in Python, can anyone give me some advice?我是用 Python 编写和阅读文件的新手,谁能给我一些建议?
Thanks in advance.提前致谢。
You still need to output the changes back into the CSV files.您仍然需要将更改输出回 CSV 文件。
What you've done so far is to read the data from the CSV files into dataframes in Python, located in memory.到目前为止,您所做的是将 CSV 文件中的数据读取到 Python 中位于内存中的数据帧中。 Then you change them up.然后你改变它们。 But then you stopped.但后来你停了下来。 After your for loop, you should then output the changed data1
back to CSV.在 for 循环之后,您应该将更改后的data1
输出回 CSV。 For example:例如:
data1.to_csv('Big_File.csv')
Here are the docs on to_csv
https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.DataFrame.to_csv.html以下是to_csv
https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.DataFrame.to_csv.html上的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.