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位数字(年份)。我该怎么办?。
导入
1 | df.iloc[:,3].astype(str).apply(lambda row: re.sub(r'(?<!\\S)\\d+(?!\\S)', lambda x: p.number_to_words(x.group()), row)) |
首先,使用