关于regex:pandas在每一行和每一列中将数字转换为单词

pandas convert numbers to words in every rows and one specific column

更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

我有一个熊猫数据框,某些行的某些列中包含数字。我想使用inflect库仅用相应的单词表示形式替换数字。

我认为df.replace很合适。但是我怎么只能指定数字
(所有用空格分隔的数字)应被替换,并将其作为拐点传递给参数?。

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

类似地,我有第二个数据框,在这里我想为特定列(索引为4的列)执行此操作。该列仅包含4位数字(年份)。我该怎么办?。


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

1
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)将列强制转换为字符串。然后,每个row中的(?<!\\S)\\d+(?!\\S)匹配,并且数字被发送到.number_to_words()方法。