我的 df 中有一个“Vol”列,其中的值以 K 和 M 结尾,分别表示千和百万,这些值是 dtype 中的“object”,我需要将它们转换为“double”。
Example for the column what I need it to look like
Vol Result
920.81K 920810
1.28M 1200000
2.19M 2190000
443.66K 443660
682.81K 682810
最佳答案
有几种方法可以做到这一点。我最喜欢的是使用 replace
和 pd.eval
。假设“Vol”是一个字符串列,您可以这样做:
df['Vol'].replace({'K': '*1e3', 'M': '*1e6'}, regex=True).map(pd.eval)
0 920810.0
1 1280000.0
2 2190000.0
3 443660.0
4 682810.0
Name: Vol, dtype: float64
根据您需要支持的数量级,您可以根据需要修改替换字典。
关于python - 如何使用 pandas 将 200.13K 和 1.2M 等数字字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542176/