通过For循环修改熊猫系列

时间:2020-02-06 11:11:48

标签: python pandas

我有一个带有商品详细信息的Pandas DataFrame。其中一栏是“重量”,一些值分别以200kgs,120kgs等存储在“重量”列中。

我想剥离'kgs'字符串,以便可以将这些值用于某些计算。我尝试通过For循环执行同样操作以剥离“ kgs”

item = pd.read_csv('item_data.csv') 

for x in item.Weight:  # item.Weight shows the weights of the items
    if type(x) == str:
        item.Weight = x.strip('kgs')
    else:
        item.Weight =  x

以上代码剥离了“ kgs”,但显示了所有行的第一个值!

item.Weight = [x.strip('kgs') if type(x)==str else x for x in item.Weight]

但是,当我进行列表理解时,如上所示,它可以工作!您能解释一下为什么For循环似乎不起作用但具有相同逻辑的List Comprehension有效吗

4 个答案:

答案 0 :(得分:1)

使用:

item['Weight']=item.Weight.str.strip('kgs')

答案 1 :(得分:0)

有一个内置方法.str.strip() 尝试:

item.str.rstrip('kgs')

答案 2 :(得分:0)

使用Series.str.rstrip 删除值的右侧的公斤

item['Weight']=item.Weight.str.rstrip('kgs')

然后可以使用Series.astype转换为floatint

item['Weight']=item.Weight.str.rstrip('kgs').astype(float)
#item['Weight']=item.Weight.str.rstrip('kgs').astype(int)

pd.to_numericerrors = 'coerce' 然后检查是否有任何NaN值以及它的来源。

item['Weight']=pd.to_numeric(item.Weight.str.rstrip('kgs'),errors = 'coerce')

答案 3 :(得分:0)

在列表理解方法中,您基本上是在创建完整列表并分配给权重列,以便按预期方式工作。.尽管其他答案中提到的方法更有效。

第一种方法不起作用,因为您一次将一个权重分配给整个列而不是列表。