【问题标题】:Get numeric part of string column and cast to integer获取字符串列的数字部分并转换为整数
【发布时间】:2020-06-25 09:53:33
【问题描述】:

这个问题其实很简单,我就是想不通。有一个 我使用的国际足联数据集,我想将所有 weight 列转换为整数。所以:首先我删除lbs,然后我转换为整数。

fifa["Weight"].head()
           
    0    159lbs
    1    183lbs
    2    150lbs
    3    168lbs
    4    154lbs
    Name: Weight, dtype: object


fifa.Weight = [int(x.strip("lbs")) if type(x)==str else x for x in fifa.Weight] 

我知道我可以使用它,但我不想。

fifa_weight =[]

for i in fifa["Weight"]:

    if(type(i)==str):

        fifa_weight.append(int(i.strip("lbs")))

## There are some missing values in the Weight column that's why I use type(i)==str.

我在fifa["Weight"] 列中获取值并尝试将其放在fifa_weight 列中,但我无法更改列(因为缺少值)所以.. 我该怎么做循环?我希望我的 fifa["Weight"] 列充满整数。

【问题讨论】:

  • 哇.. 简直不敢相信解决方案这么简单!非常感谢!

标签: python pandas numpy dataframe data-analysis


【解决方案1】:
>>> fifa
   Weight
0  159lbs
1  183lbs
2  150lbs
3  168lbs
4  154lbs

fifa["Weight"] = fifa["Weight"].str.replace("lbs", "") 

然后

fifa["Weight"] = fifa["Weight"].astype(float)

如果权重列中有空单元格,请先用占位符(如 -9999)或其他内容填充它,然后尝试上述方法;

【讨论】:

    【解决方案2】:

    给定

    >>> df
       Weight
    0  159lbs
    1  183lbs
    2  150lbs
    3  168lbs
    4  154lbs
    

    你可以去掉最后三个字符,然后通过

    将字符串转换为整数
    >>> df['Weight'] = df['Weight'].str[:-3].astype(int)
    >>> df
       Weight
    0     159
    1     183
    2     150
    3     168
    4     154
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2019-12-19
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多