gpt4 book ai didi

python - 如何将值解析为带有列名的csv

转载 作者:行者123 更新时间:2023-12-02 06:25:17 24 4
gpt4 key购买 nike

我想更新 csv 文件中的特定列。我想更新函数 func1 中的第一列和函数 func2 中的第二列:

def func1(x):
data = 'test1'
file = open("test.csv","a+")
file.write(data)
file.close()
return data

def func2(x):
data = 'test2'
file = open("test.csv","a+")
file.write(data)
file.close()
return data

预期结果

col1,col2
test1,test2

如何指定要更新的列?此处,没有创建任何文件。

最佳答案

您可以使用pandas包来更新特定列(如果您没有它,您可以通过在终端中运行pip install pandas来安装它):

import pandas as pd

def func1(file):
column = 'col1'
data = 'new_test1'
file[column] = data
return data
def func2(file):
column = 'col2'
data = 'new_test2'
file[column] = data
return data

# you should open the file only once, you don't need to open it seperately within each function
df = pd.read_csv('data.csv')

print(df)
# col1 col2
# 0 test1 test2
# the '0' is an index column, you can remove it when writing to the file (using index=False, see below)

data1 = func1 (df)
data2 = func2 (df)

df.to_csv('data.csv', index=False) # with 'index=False' you won't see an index column in data.csv

print(df)
# col1 col2
# 0 new_test1 new_test2

This question可能对你也有用

关于python - 如何将值解析为带有列名的csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59458312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com