在 DataFrame 上应用函数后,在 DataFrame 中就地更改系列 [英] Change Series inplace in DataFrame after applying function on it
本文介绍了在 DataFrame 上应用函数后,在 DataFrame 中就地更改系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 pandas
以便使用简单的函数就地更改我的一列.
I'm trying to use pandas
in order to change one of my columns in-place, using simple function.
在阅读了整个 Dataframe 后,我尝试在一个系列上应用函数:
After reading the whole Dataframe, I tried to apply function on one Serie:
wanted_data.age.apply(lambda x: x+1)
而且效果很好.当我尝试将它放回我的 DataFrame 时,会出现唯一的问题:
And it's working great. The only problem occurs when I try to put it back into my DataFrame:
wanted_data.age = wanted_data.age.apply(lambda x: x+1)
或:
wanted_data['age'] = wanted_data.age.apply(lambda x: x+1)
抛出以下警告:
> C:\Anaconda\lib\site-packages\pandas\core\generic.py:1974:
> SettingWithCopyWarning: A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] =
> value instead
>
> See the the caveats in the documentation:
> http://pandas.pydata.org/pandas-docs/stable
> /indexing.html#indexing-view-versus-copy self[name] = value
当然,我可以使用以下长格式设置DataFrame:
Of Course, I can set the DataFrame using the long form of:
wanted_data.loc[:, 'age'] = wanted_data.age.apply(lambda x: x+1)
但是有没有其他更简单、更语法更好的方法来做到这一点?
But is there no other, easier and more syntactic-nicer way to do it?
谢谢!
推荐答案
使用loc
:
wanted_data.loc[:, 'age'] = wanted_data.age.apply(lambda x: x + 1)
这篇关于在 DataFrame 上应用函数后,在 DataFrame 中就地更改系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文