change column values in CSV using python

2019-09-12 07:28发布

Let say this in the input CSV file.

enter image description here

I would like to go over the Babys column and change it to increasing number by 1.

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")

标签: python csv row
2条回答
ら.Afraid
2楼-- · 2019-09-12 08:09

You can use python pandas to increase the column number by n:

import pandas
data_df = pandas.read_csv('input.csv')
data_df = data_df['age'].apply(lambda x: x+n)
print data_df

for adding 1 replace n by 1.

查看更多
三岁会撩人
3楼-- · 2019-09-12 08:10

It can be done very easily when using pandas module

import pandas as pd

# read/parse CSV into pandas data frame
df = pd.read_csv('input.csv', delim_whitespace=True)

Output:

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

Output:

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

increase Babys column by 1 for all rows (unconditionally)

df.Babys += 1

Output:

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

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
查看更多
登录 后发表回答