我有一个dataFrame live(活产)和一个列' agepreg'这是一个带有两位小数的浮点数。我想创建一个新专栏' agepreg_rounded'作为整数。
我天真的做法:
live['agepreg_rounded'] = live['agepreg'].apply(lambda x: round(x,0))
是否有效,但会发出警告:
/usr/local/lib/python3.5/dist-packages/ipykernel/__main__.py:4: 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 caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
我已多次尝试使用.loc语法,但失败了。
有人能帮我直接吗?
这是我试图写的那种东西,但这显然是错误的:
live['agepreg_rounded'] = live.loc[live['agepreg']].apply(lambda x: round(x,0))
更新:直播来自哪里?
我正在关注来自O' Reilly的ThinkStats2书,数据来自使用源材料下载的文件:
import nsfg
preg = nsfg.ReadFemPreg()
live = preg[preg.outcome == 1]
答案 0 :(得分:1)
我认为您需要copy
,然后apply
使用Series.round
:
live = preg[preg.outcome == 1].copy()
live['agepreg_rounded'] = live['agepreg'].round(0)
如果稍后修改live
中的值,您会发现修改不会传播回原始数据(preg
),并且Pandas会发出警告。