【问题标题】:How to change DataFrame column dtype with regex and lambda expression?如何使用正则表达式和 lambda 表达式更改 DataFrame 列 dtype?
【发布时间】:2021-09-02 21:32:58
【问题描述】:

考虑以下DataFrame:

df = pd.DataFrame({'a':['123','667','323'],
                   'b':['8000','1. 300', '56'],
                   'c':['11','apple', '100']})

#      a       b      c
# 0  123    8000     11
# 1  667  1. 300  apple
# 2  323      56    100

如果它是一串数字,我想将数据类型更改为 int。正则表达式很简单:

pattern = '^\d+$'
df.apply(lambda x: x.str.match(pattern, flags=re.IGNORECASE))

如何将任何匹配的列的数据类型更改为int(本例中的列a)?列名不一致,因此我无法对其进行硬编码。这里需要applymap吗?

【问题讨论】:

  • 请发布预期输出
  • 为什么不只是df[col].astype(int, errors='ignore')?

标签: python regex pandas


【解决方案1】:

你可以尝试在每一列上使用.apply()来使用.astype(),如下:

df = df.apply(lambda x: x.astype(int, errors='ignore'))

结果:

df.to_dict()

{'a': {0: 123, 1: 667, 2: 323},          
 'b': {0: '8000', 1: '1. 300', 2: '56'},
 'c': {0: '11', 1: 'apple', 2: '100'}}

a 列已转换为int 类型。


我们还可以利用您的方法将列转换为int,然后相应地转换列:

在默认的axis=0 上使用.all() 来标记所有行元素与您的正则表达式模式匹配的列。然后,使用.loc 定位这些列并将列名放入列表cols。然后,在此列列表中使用.astype() 将类型转换为int

import re

pattern = '^\d+$'
cols = df.loc[:, df.apply(lambda x: x.str.match(pattern, flags=re.IGNORECASE)).all()].columns

df[cols] = df[cols].astype(int)

结果:

df.to_dict()

{'a': {0: 123, 1: 667, 2: 323},          
 'b': {0: '8000', 1: '1. 300', 2: '56'},
 'c': {0: '11', 1: 'apple', 2: '100'}}

【讨论】:

    【解决方案2】:

    您可能正在寻找pd.to_numeric():

    ret = df.apply(pd.to_numeric, errors="ignore")
    print(ret.dtypes)
    

    上述表达式将pd.to_numeric() 应用于数据框的每一列,请参阅pd.DataFrame.apply(fun, **kwargs)。这大致相当于 .csv 文件中 numeric 数据的 pd.read_csv() 的 dtype 推断。使用pd.to_numeric(),您可以将不匹配的表达式转换为NaN(设置errors="coerce"),或对推断类型应用额外的向下转换(添加参数downcast="signed")。

    我发现这并不能完全回答 OP 的问题(不涉及正则表达式)。但是,我宁愿使用 pandas 提供的数据类型推断功能,也不愿自己开发。

    【讨论】:

    • 我在搜索时看到了 pd.to_numeric,但由于其他字符串,我认为它不会起作用。 errors="ignore" 很有帮助,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2017-01-18
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多