【发布时间】: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'(?<!\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'(?<!\S)\d+(?!\S)'。我的意思是,正则表达式仅适用于字符串,因此您需要将字符串传递给在幕后使用的re.sub。
标签: regex python-2.7 pandas dataframe replace