change column values in CSV using python

后端 未结 2 751
孤城傲影
孤城傲影 2020-12-22 09:12

Let say this in the input CSV file.

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

what i did is to

相关标签:
2条回答
  • 2020-12-22 09:38

    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.

    0 讨论(0)
  • 2020-12-22 09:47

    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
    
    0 讨论(0)
提交回复
热议问题