首页 > 解决方案 > 函数内的临时 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)(我理解这是不好的做法),还是有更聪明的方法?

标签: pythonpandas

解决方案


推荐阅读