简体   繁体   中英

Errors When Creating A Column Which Is The Difference Between Two Columns

if I have a dataframe and I want to create a new column of the same dataframe whose result is row-wise result is column1 - column 2, what is the best code to accomplish this? column1 and column2 have NaNs in them so I believe that's why I'm getting errors.

THanks, Ben

Here is my dataframe

>>> frame2
   col1  col2  col3
0   NaN   NaN     8
1     2     5     9
2   NaN   NaN    10
3     4     7    11
4   NaN   NaN    12

I'm getting the following error

TypeError: unsupported operand type(s) for -: 'str' and 'str'

To subtract, say, col1 and col2 , try `astype(float):

df.col1.astype(float) - df.col2.astype(float)

Your columns look like numbers, but they are actually strings, according to the message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM