【发布时间】:2021-08-25 17:17:18
【问题描述】:
我正在做一个练习熊猫的个人项目,还有美丽的汤,我把这个信息刮下来,把它放在熊猫 df 中,如下所示:
0 €8.5M
1 €0
2 €9.5M
3 €2M
4 €21M
...
16534 €1.8M
16535 €1.1M
16536 €550K
16537 €650K
16538 €1.1M
Name: Value, Length: 16539, dtype: object
0 €67K
1 €0
2 €15K
3 €11K
4 €13K
...
16534 €3K
16535 €2K
16536 €2K
16537 €7K
16538 €3K
Name: Wage, Length: 16539, dtype: object
所以为了分析这些信息,我想清理这些数据并将其转换为整数,我能想到的是:
df['Wage'] = df['Wage'].apply(lambda x: re.sub('€','',x))
df['Wage'] = df['Wage'].apply(lambda x: re.sub('K','000',x))
df['Value'] = df['Value'].apply(lambda x: re.sub('€','',x))
df['Value'] = df['Value'].apply(lambda x : re.sub('M','00000',x) if (('M' in x) and ('.' in x))else x)
df['Value'] = df['Value'].apply(lambda x : re.sub('[.]','',x))
df['Value'] = df['Value'].apply(lambda x : re.sub('M','000000',x))
df['Value'] = df['Value'].apply(lambda x : re.sub('K','000',x))
df['Wage'] = df['Wage'].astype(int)
df['Value'] = df['Value'].astype(int)
我首先替换了货币符号,然后检查点,以便我可以将 M 替换为 5 个零,然后将剩余的 M 替换为 6 个零,然后将 K 替换为 3 个零,然后我将类型更改为 int。 但我觉得这不是一个好方法,你怎么看?有什么更好的方法来做到这一点?我尝试创建一个函数,但做不到。
【问题讨论】:
标签: python regex pandas dataframe