I’m trying to use pandas
in order to change one of my columns in-place, using simple function.
After reading the whole Dataframe, I tried to apply function on one Series:
JavaScript
x
2
1
wanted_data.age.apply(lambda x: x+1)
2
And it’s working great. The only problem occurs when I try to put it back into my DataFrame:
JavaScript
1
2
1
wanted_data.age = wanted_data.age.apply(lambda x: x+1)
2
or:
JavaScript
1
2
1
wanted_data['age'] = wanted_data.age.apply(lambda x: x+1)
2
Throwing the following warning:
JavaScript
1
9
1
> C:Anacondalibsite-packagespandascoregeneric.py:1974:
2
> SettingWithCopyWarning: A value is trying to be set on a copy of a
3
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] =
4
> value instead
5
>
6
> See the the caveats in the documentation:
7
> http://pandas.pydata.org/pandas-docs/stable
8
> /indexing.html#indexing-view-versus-copy self[name] = value
9
Of Course, I can set the DataFrame using the long form of:
JavaScript
1
2
1
wanted_data.loc[:, 'age'] = wanted_data.age.apply(lambda x: x+1)
2
But is there no other, easier and more syntactic-nicer way to do it?
Thanks!
Advertisement
Answer
Use loc
:
JavaScript
1
2
1
wanted_data.loc[:, 'age'] = wanted_data.age.apply(lambda x: x + 1)
2