1

I have a dataframe like this:

A     B     C

15   'ds'   '    0.000'
32   'ds'   '    1.000'
56   'ds'   '    2,700.000'
45   'gb'   '    7.000'

I want to change the values of column C to integers; so what i'm doing is something like this:

df.loc[:,'C'] = df.loc[:,'C'].apply(lambda x: int(float(x.strip().replace(',',''))))

This do the job, however, i get that annoying SettingWithCopyWarning. Why this appear if i'm using loc?

2 Answers 2

2

Pandas raises this warning in some cases with false positive (i.e. when, based on the order of assignments, you could be assigning to a copy, but in the current scenario aren't). This answer is helpful: How to deal with SettingWithCopyWarning in Pandas?

... but, personally, when I'm using .loc and still receiving the warning, I take the step offered in the above answer and disable the warning: pd.options.mode.chained_assignment = None

1

I'd use the following approach:

In [292]: df['C'] = pd.to_numeric(df['C'].str.strip().str.replace(',', ''), errors='coerce')

In [293]: df
Out[293]:
    A   B       C
0  15  ds     0.0
1  32  ds     1.0
2  56  ds  2700.0
3  45  gb     7.0

In [294]: df.dtypes
Out[294]:
A      int64
B     object
C    float64
dtype: object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.