1

Following this thread, Change data type of columns in Pandas (btw I didn't answer on this topic and created a new one as I didn' find a way to ask new questions on an existing, but if I did wrong and should have followed the thread, please let me know how I should do).

I'm working on a pricing tool and reading pricing tables.

Having read a csv with pandas, I'm trying to convert string to float but for specific rows only.

Indeed, I have in the same column both string and float, although they all look like float. For instance, I have ZIPCode, which are to be considered as string, and float number in the same column (for TCC type rows, Value is a float in the example) :

my df

Of course, I have several thousands of lines in my df so I've tried to sum it up.

I've tried the following but this doesn't work:

df.loc[df.loc[:, 'Type'] == 'TCC']['Value'].apply(pd.to_numeric, errors='ignore')

This doesn't work either :

df.loc[df.loc[:, 'Type'] == 'TCC']['Value'] = df.loc[df.loc[:, 'Type'] == 'TCC']['Value'].apply(pd.to_numeric, errors='ignore')

Would you have an idea how to do so ?

yeye
  • 503
  • 4
  • 19
  • 1
    You can't. In your example, `Value` looks like it could be cast to a float type, but you can't have columns with mixed types – roganjosh Apr 12 '19 at 07:48
  • If you want to sum the `Value` values then you could `groupby(Type)` and apply some function on `Values` using `.astype(float)` – roganjosh Apr 12 '19 at 07:50
  • You can use `if type(df.iloc[row][col]) == string` then do some action to convert value. Make `for` loop to iterate over the dataframe. – YusufUMS Apr 12 '19 at 08:02
  • 2
    @Yusufsn you might as well not be working with Pandas in that case. It is not really designed for iterating over rows – roganjosh Apr 12 '19 at 08:04
  • yes i'd rather not use a for loop I've found an alternative way doing what I wanted later in my code when I split my mainDF into subDF. However, when you say there can be only one type, how does it work with the pd.to_numeric() ? I've tried it and I have both strings and float in the columns, unless I'm wrong ? – yeye Apr 12 '19 at 12:12

0 Answers0