Converting DataFrame values to int, adding them and create new column with result?

前端 未结 1 1755
广开言路
广开言路 2021-01-22 21:56

I have a very large dataframe of string numbers, something like for example:

a,b,c
\"1\",\"2\",\"3\"
\"4\",\"5\",\"6\"
\"7\",\"8\",\"9\"

And I

相关标签:
1条回答
  • 2021-01-22 22:32

    In my opinion read_csv convert columns to integers.

    So use:

    df = pd.read_csv(file)
    df['d'] = df['a'] + df['c']
    

    But if failed, then try convert to integer or floats:

    df = pd.read_csv(file)
    df['d'] = df['a'].astype(int) + df['c'].astype(int)
    #floats 
    #df['d'] = df['a'].astype(float) + df['c'].astype(float)
    

    If there are also some strings between numeric is possible convert problems values to NaNs and sum:

    df = pd.read_csv(file)
    df['d'] = pd.to_numeric(df['a'], errors='coerce') + pd.to_numeric(df['c'],  errors='coerce')
    
    0 讨论(0)
提交回复
热议问题