python - 函数内的临时 DataFrame 子集修改
问题描述
我的问题不是关于如何处理SettingWithCopyWarning
。这是在特定情况下如何最好地处理它。
我有一个传递整个 DataFrame 的函数。作为该函数的一部分,我将只保留一个子集,然后在返回最终结果之前修改一列。正如预期的那样,这会触发SettingWithCopyWarning
.
我的意思是......是的,这就是重点:我想在不实际接触源的情况下处理我的 DataFrame 的块(从而修改副本),同时在处理每个块后清除内存(因此是函数)。这是一个插图:
In [1]: import pandas as pd
In [2]: def add_one(df, column):
...: df = df[df['A']==1]
...: df['A'] = df['A'] + 1
...: print(df['A'])
...:
In [3]: test_df = pd.DataFrame({'A': [1,1,2]})
In [4]: add_one(test_df, 'A')
0 2
1 2
Name: A, dtype: int64
/tmp/ipykernel_132006/2423483857.py:3: 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
df['A'] = df['A'] + 1
In [5]: test_df
Out[5]:
A
0 1
1 1
2 2
我应该只支持警告pd.set_option('mode.chained_assignment', None)
(我理解这是不好的做法),还是有更聪明的方法?
解决方案
推荐阅读
- python - 无法使用 xPath 定位元素
- python - 如何从原始图像文件中获取每像素 10 位?
- c# - 界面中的列表
- regex - 在不复制表达式的情况下,强制正则表达式用引号括起来或根本不用引号
- r - 当某些观察值少于 n 行时,使用 dplyr 在数据帧中对每组随机采样 n 行
- python - OpenCV中PIL库函数ImageEnhance.Contrast(image).enhance(param)的等价物是什么?
- c# - 无法将列表附加到现有文件。C#
- r - 使用点 (...) 将不同的参数传递给内部函数
- jenkins - 错误无法建立一个或多个指定的浏览器连接。这可能是由网络问题或远程设备故障引起的
- reflection - Threejs:glb文件反映环境但不反映自身