Skip to main content
 首页 » 编程设计

python之分配给 Pandas 中的容器

2025年05月04日13bluestorm

我想用空列表替换 Pandas 中特定列中的 None 条目。

请注意,此列中的某些条目可能已经有一个空列表,我不想碰那些。

我试过:

indices = np.equal(df[col],None) 
df[col][indices] = [] 

和

indices = np.equal(df[col],None) 
df[col][indices] = list() 

但两种解决方案都失败了:

ValueError: Length of replacements must equal series length 

为什么?如何使用空列表更新这些特定行?

请您参考如下方法:

在作业中不允许使用地方性列表,也不建议这样做。

如果您从头开始创建,您可以做到这一点

In [50]: DataFrame({ 'A' : [[],[],1]}) 
Out[50]:  
    A 
0  [] 
1  [] 
2   1 
 
[3 rows x 1 columns] 

不允许这样做的原因是没有索引(例如在 numpy 中说),你可以这样做:

In [51]: df = DataFrame({ 'A' : [1,2,3] }) 
 
In [52]: df.loc[df['A'] == 2] = [ 5 ] 
 
In [53]: df 
Out[53]:  
   A 
0  1 
1  5 
2  3 
 
[3 rows x 1 columns] 

你可以做一个赋值,其中掩码中真值的长度等于 rhs 上列表/元组/ndarray 的长度(例如你正在设置的值)。 Pandas 允许这个,以及一个恰好等于 lhs 的长度和一个标量。任何其他内容都被明确禁止,因为它含糊不清(例如,你的意思是对齐还是不对齐?)

例如,想象一下:

In [54]: df = DataFrame({ 'A' : [1,2,3] }) 
 
In [55]: df.loc[df['A']<3] = [5] 
ValueError: cannot set using a list-like indexer with a different length than the value 

一个 0 长度的列表/元组/ndarray 被认为是一个错误,不是因为它不能完成,而是通常它的用户错误,不清楚该做什么。

最重要的是,不要在 pandas 对象的内部使用列表。它效率不高,只会使解释变得困难/不可能。