使用python更改CSV中的列值 [英] change column values in CSV using python
本文介绍了使用python更改CSV中的列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请在输入的CSV文件中说出。
Let say this in the input CSV file.
我想浏览 Babys
栏,并将其改为数字增加1。
I would like to go over the Babys
column and change it to increasing number by 1.
我做的是计算在文件中有多少行,并对所有的运行一个for循环。
但我不知道如何更改值
what i did is to count how many row there are in the file, and run a for loop on all of them. But i cant figure out how to change the values
v = open(input.csv)
r=csv.reader(v)
numline = len(v.readlines())
print (numline)
for row in r:
if row["Baby"] == "Baby":
for i in range (1, numline):
print("test")
$ b b
推荐答案
使用 pandas 模块
将pandas导入为pd
import pandas as pd
# read/parse CSV into pandas data frame
df = pd.read_csv('input.csv', delim_whitespace=True)
输出:
In [33]: df
Out[33]:
Name Age Babys
0 Avi 25 1
1 Dav 24 1
2 Ela 30 1
3 Ron 40 1
4 Shi 33 1
5 Leb 22 1
6 Moe 11 1
有条件地增加
conditionally increase Babys
column by 1
df.loc[(df.Name.isin(['Avi','Dav','Ron'])) & (df.Age < 33), 'Babys'] += 1
输出:
In [35]: df
Out[35]:
Name Age Babys
0 Avi 25 2
1 Dav 24 2
2 Ela 30 1
3 Ron 40 1
4 Shi 33 1
5 Leb 22 1
6 Moe 11 1
增加 Babys
>
df.Babys += 1
输出:
In [43]: df
Out[43]:
Name Age Babys
0 Avi 25 3
1 Dav 24 3
2 Ela 30 2
3 Ron 40 2
4 Shi 33 2
5 Leb 22 2
6 Moe 11 2
最后将更改的DF保存为CSV文件:
Finally save changed DF back to CSV file:
df.to_csv('d:/temp/out.csv', index=False, sep=',')
out.csv:
Name,Age,Babys
Avi,25,3
Dav,24,3
Ela,30,2
Ron,40,2
Shi,33,2
Leb,22,2
Moe,11,2
这篇关于使用python更改CSV中的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文