1

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")
2
  • 1
    Please provide attempted code with error messages if any, consider reading stackoverflow.com/help/mcve, thanks Commented May 26, 2016 at 6:29
  • And please don't include such a simple CSV as an image. It can easily be included as a code block. Commented May 26, 2016 at 8:09

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.