pandas - SettingWithCopyWarning:试图在 DataFrame 中的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value
问题描述
问题
- 我已经阅读了所有可能的解决方案,以消除警告 “SettingWithCopyWarning:试图在 DataFrame 的切片副本上设置值。尝试使用 .loc[row_indexer,col_indexer] = value 代替”
但没有任何效果,我无法摆脱错误消息。
非常感谢您投入的时间帮助我,当然还有更多的人
我使用哪些工具
我正在使用kaggle运行笔记本,配置很简单,我没有加载任何库
目标
我想舍入一列并用结果创建一个新列
数据
id; city.coord.lon; city.coord.lat
12957; 4.32664; 51.219791
12958; 3.33848; 50.812679
12959; 3.81052; 50.869560
df_weather_in_cities 是如何创建的?
# load the history city list
with open(history_city_list_path) as f:
d = json.load(f)
df_weather_in_cities = pd.json_normalize(d)
# filter the belgian cities
df_cities_weather_in_be = df_weather_in_cities[df_weather_in_cities['city.country']=='BE']
df_weather_in_cities 的 dtypes 是什么?
id float64
city.name object
city.coord.lon float64
city.coord.lat float64
dtype: object
代码 #1,在右侧使用 .loc
df_cities_weather_in_be['lat_rounded'] = df_cities_weather_in_be.loc[:,('city.coord.lat')].apply(lambda x: np.round(x, 4))
代码 #2,使用简单的列选择
df_cities_weather_in_be['long_rounded'] = df_cities_weather_in_be['city.coord.lat'].apply(lambda x: np.round(x, 4))
代码 #3,在左侧使用 .loc
df_cities_weather_in_be.loc[:,'long_rounded'] = df_cities_weather_in_be['city.coord.lat'].apply (lambda x: np.round(x, 4))
代码#4,两边都使用 .loc
df_cities_weather_in_be.loc[:,'long_rounded'] = np.round(df_cities_weather_in_be.loc[:,'city.coord.lat'], 4)
错误
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:1: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
"""Entry point for launching an IPython kernel.
解决方案
推荐阅读
- r - 如何在决策树中找到正确分类的候选人数量?
- c++ - 将 WinAPI HWND 窗口句柄作为变量存储在类中
- python - 修复嵌套 For 循环的字典理解
- python - 有没有更好的方法来沿第一维将两个 Pytorch 张量相乘和求和?
- java - 为什么Hashset删除重复对象不起作用
- swift - 与其他视图重叠的动态文本编辑器
- kubernetes - Kubernetes:由于证书问题,无法下载法兰绒 CNI
- .net - IIS 应用程序池标识不适用于 .NET CORE?
- javascript - 无法访问 redux 道具
- php - 在一行代码上创建一个带有两个 wordpress 错误的元框