【问题标题】:How to insert a certain value to rows in pandas如何在熊猫的行中插入某个值
【发布时间】:2020-07-02 10:53:01
【问题描述】:

我想将一列从 str 更改为 float。该列现在有后缀为“M”或“K”的数字,我想删除并只保留数字,以及一个我想替换为 0 的字符串。

1) 为了去除字符 M 和 K,我使用了它:

apps["Size"] = apps["Size"].map(lambda x: x.lstrip('M').rstrip('M'))
apps["Size"] = apps["Size"].map(lambda x: x.lstrip('K').rstrip('K'))

2) 为了将值从“Varies with device”更改为 0,我尝试使用这个:

mask = apps["Size"] == 'Varies with device'
apps.loc[mask, apps["Size"]] = '0'

我做错了什么?有没有更简单的方法来改变它?

谢谢!

【问题讨论】:

    标签: python pandas replace pandas-loc


    【解决方案1】:

    Series.str.strip 删除单位,然后用to_numericerrors='coerce' 将值转换为数字,将另一个非数字值转换为缺失值,然后用Series.fillna 替换:

    apps["Size"] = pd.to_numeric(apps["Size"].str.strip('KM'), errors='coerce').fillna(0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2019-11-21
      • 2019-01-25
      相关资源
      最近更新 更多