Skip to main content
 首页 » 编程设计

python之Pandas :更改列数据类型会产生警告

2025年05月04日13xing901022

假设我有以下 pandas DataFrame:

df = pd.DataFrame({'one': ['Baseline', 5, 6], 'two': [10, 10, 10]}) 
print(df) 
print(df.dtypes) 
#  one    object 
#  two     int64 

我想收集所有 df.one != 'Baseline' 的行,然后将这个新数据框中的 one 列转换为 int 数据类型。我假设以下会正常工作,但当我尝试将 int 转换为 one 时,我收到了 SettingWithCopyWarning 投诉:

df_sub = df[df['one'] != 'Baseline'] 
df_sub['one'] = df_sub['one'].astype(int) 
 
script.py:15. 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 
   df_sub['one'] = df_sub['one'].astype(int) 

代码似乎工作正常(见下文)但我想知道如何避免此警告(我应该使用不同的方法等)。我正在关注 this question用于更改特定列的数据类型。我也尝试过 df_sub.loc[:, 'one'] = df_sub['one'].astype(int) 和 df_sub.loc[:, 'one'] = df_sub .loc[:, 'one'].astype(int) 我遇到了同样的错误。

print(df_sub.dtypes) 
#  one     int64 
#  two     int64 

请您参考如下方法:

为了避免该警告,请复制您的数据框

df_sub = df[df['one'] != 'Baseline'].copy() # A deep copy of your dataframe otherwise it'll point to an existing one in memory.