Pandas Dataframe: Replace charactere conditionally

▼魔方 西西 提交于 2019-12-11 02:06:20

问题


I have a dataframe with a column named "Size". This column have some values containing the size of an android applications list.

Size
8.7M
68M
2M

I need to replace these values to:

Size:
8700000
68000000
...

I thought about a function that verifies if there is a dot at the string '.'. If it exists, change the M value to five zero's (00000). If not, change the M value to six zero's (000000). Could you guys help me with it?


回答1:


General solution for replace by multiple units:

#dict for replace
_prefix = {'k': 1e3,    # kilo
           'M': 1e6,    # mega
           'B': 1e9,    # giga
}
#all keys of dict separated by | (or)
k = '|'.join(_prefix.keys())
#extract values to new df
df1 = df['Size'].str.extract('(?P<a>[0-9.]*)(?P<b>' + k +')*', expand=True)
#convert numeric column to float
df1.a = df1.a.astype(float)
#map values by dictionary, replace NaN (no prefix) to 1
df1.b = df1.b.map(_prefix).fillna(1)
#multiple columns together
df['Size'] = df1.a.mul(df1.b).astype(int)
print (df)
       Size
0   8700000
1  68000000
2   2000000

If want only replace M solution should be simplified:

df['Size'] = df['Size'].str.replace('M', '').astype(float).mul(1e6).astype(int)
print (df)
       Size
0   8700000
1  68000000
2   2000000


来源:https://stackoverflow.com/questions/53142947/pandas-dataframe-replace-charactere-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!