ASH
ASH

Reputation: 20302

Can we set a specific column AND row for pd.to_numeric?

I'm wondering if there is a way to set a range for pd.to_numeric to run over, but exclude one column and 2 rows? I know you can do this in Excel; I don't know if it's possible to do in pd.to_numeric. For instance, I want to convert everything in a data frame to numeric, EXCEPT for the very last column in the data frame and EXCEPT for the first two rows in the data frame.

Here is the code that I am experimenting with.

cols = df_append.columns[:-1]
rows = df_append.iloc[2:]
df_append[cols] = df_append[cols].apply(pd.to_numeric, errors='coerce')
df_append[rows] = df_append[rows].apply(pd.to_numeric, errors='coerce')
df_append = df_append.fillna(0)
df_append.head()

I would like to convert everything to numeric below row two and to the left of the very last column.

Upvotes: 0

Views: 341

Answers (1)

Chris
Chris

Reputation: 16147

This should work:

import pandas as pd
    
df = pd.DataFrame(
    {"A": ['A','B','C','D','E'],
     'B':['A','B','C','D','E'],
     'C':['A','B','C','D','E']
            })

df.iloc[2:, :-1] = df.iloc[2:, :-1].apply(pd.to_numeric, errors='coerce')

Output

    A   B   C
0   A   A   A
1   B   B   B
2   NaN NaN C
3   NaN NaN D
4   NaN NaN E

Upvotes: 1

Related Questions