Skip to main content
 首页 » 编程设计

python之根据条件更新 Pandas 数据框的值

2025年05月04日35zhwl

我正在尝试按逻辑条件更新 pandas 数据框,但失败并出现以下错误,

df[df.b <= 0]['b'] = 0 

试图在 DataFrame 的切片副本上设置一个值。尝试使用 .loc[row_indexer,col_indexer] = value 代替

我如何让它工作?

数据:

df = pd.DataFrame({'a': np.random.randn(4), 'b': np.random.randn(4)}) 
    a           b 
0   1.462028    -1.337630 
1   0.206193    -1.060710 
2   -0.464847   -1.881426 
3   0.290627    0.650805 

我正在学习 Pandas 。在 R 中,语法如下所示,

df[df$b <= 0]$b <- 0 

请您参考如下方法:

使用

df.loc[df.b <= 0, 'b']= 0 

为了提高效率,pandas 只是从以前的 DataFrame 中创建一个引用,而不是在每次应用过滤器时都创建新的 DataFrame。
因此,当您为 DataFrame 赋值时,它需要在源 DataFrame 中更新(而不仅仅是它的当前切片)。这是警告中提到的内容

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

为了避免这种 .loc 语法被使用。

有关 DataFrame indexing 的更多信息