【问题标题】:pandas convert numbers to words in every rows and one specific column熊猫将数字转换为每一行和一个特定列中的单词
【发布时间】:2018-10-04 08:41:13
【问题描述】:

更新

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.iloc[:,3].replace(r'(?<!\S)\d+(?!\S)', lambda x: p.number_to_words(x.group()), regex=True, inplace=True)
df.iloc[:,3].head(2)
0    15
1    89
Name: D, dtype: int64

df = df.astype(str)
df.iloc[:,3].replace(r'(?<!\S)\d+(?!\S)', lambda x: p.number_to_words(x.group()), regex=True, inplace=True)

df.iloc[:,3].head(2)
0    <function <lambda> at 0x7fd8a6b4db18>
1    <function <lambda> at 0x7fd8a6b4db18>
Name: D, dtype: object

我有一个 pandas 数据框,其中一些行在某些列中包含数字。我想使用屈折库仅用相应的单词表示替换数字。

我认为 df.replace 很合适。但是我怎样才能指定只有数字 (所有由空格分隔的数字)应替换并将其作为参数传递给屈折?。

p = inflect.engine()
df.replace(r' (\d+) ', p.number_to_words($1), regex=True, inplace=True)

同样,我有第二个数据框,我想针对特定列执行此操作,即索引为 4 的列。该列仅包含 4 位数字(年份)。我该怎么做?。

【问题讨论】:

  • 试试df.replace(r'(?&lt;!\S)\d+(?!\S)', lambda x: p.number_to_words(x.group()), regex=True, inplace=True)
  • @WiktorStribiżew 如果我想在只包含数字的列中替换它就不能使用(例如我的第四列包含年份,我想用单词替换它)
  • 你的意思是你有ints?那就试试casting them to string, .astype(str)。
  • @WiktorStribiżew 我想将其转换为等效的单词,而不仅仅是数据类型转换。我希望 1974 年被一千七十四取代。我试过 df.iloc[:,3].replace(r'(?=\^)\d+(?=\$)', lambda x: p.number_to_words(x.group()), regex=True, inplace =真)
  • r'(?=\^)\d+(?=\$)' 是错误的。它必须是r'(?&lt;!\S)\d+(?!\S)'。我的意思是,正则表达式仅适用于字符串,因此您需要将字符串传递给在幕后使用的re.sub。

标签: regex python-2.7 pandas dataframe replace


【解决方案1】:

导入re 库,确保您的列是string 类型,并使用(?&lt;!\S)\d+(?!\S) 匹配字符串开头/结尾和空白字符之间的数字序列。如果您只想匹配所有数字的整个条目,您可以使用^\d+$ 正则表达式。

df.iloc[:,3].astype(str).apply(lambda row: re.sub(r'(?<!\S)\d+(?!\S)', lambda x: p.number_to_words(x.group()), row))

首先,使用.astype(str) 将该列转换为字符串。然后,(?&lt;!\S)\d+(?!\S) 匹配每个row,并将号码发送到.number_to_words() 方法。

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2021-01-06
    • 2018-10-21
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多