python - 将 DataFrame 中的 pandas 系列从字符串(金融缩写)转换为数字

标签 python python-3.x pandas

<分区>

我正在尝试解析来自 NOAA 的 Storm 数据。经过一些清理和解析后,我得到了一个类似这样的 DataFrame:

import pandas as pd

data = { 'ID' : [1, 2, 3, 4, 5, 6],  
         'EVENT_TYPE': ['Flood', 'Hail', 'Fire', 'Tornado', 'Flood', 'Fire'],  
         'Property_Damage': ['2.5K', 0, '.4M', "1.00K", NaN, "1K"]}  

df = pd.DataFrame(data)  

郑重声明,此示例 DataFrame 只是一种简化。真正的 DataFrame 有大约。 25 列和 2200 万行。我想将 df['Property_Damage'] 中的值从字符串转换为数值。我想要的结果看起来类似于 [2500, 0, 400000, 1000, 0, 1000]

我知道我假设 NaN 值可以替换为 0。我试图用

将记录分成多列
damage_property_split = df['Propery_Damage'].str.split([-1], expand=True) 

但这不适用于 0NaN 的记录。

什么是最好的转换方式

['2.5K', 0, '.4M', "1.00K", NaN, "1K"][2500, 0, 400000, 1000, 0, 1000 ]

感谢您的帮助!!!

最佳答案

我很喜欢这种方法

mapping = dict(K='E3', M='E6', B='E9')

df.assign(Property_Damage=pd.to_numeric(
    df.Property_Damage.replace(mapping, regex=True)))

  EVENT_TYPE  ID  Property_Damage
0      Flood   1           2500.0
1       Hail   2              0.0
2       Fire   3         400000.0
3    Tornado   4           1000.0
4      Flood   5              NaN
5       Fire   6           1000.0

你可以用 0 填充你的 NaN

mapping = dict(K='E3', M='E6', B='E9')

df.assign(Property_Damage=pd.to_numeric(
    df.Property_Damage.fillna(0).replace(mapping, regex=True)))

  EVENT_TYPE  ID  Property_Damage
0      Flood   1           2500.0
1       Hail   2              0.0
2       Fire   3         400000.0
3    Tornado   4           1000.0
4      Flood   5              0.0
5       Fire   6           1000.0

关于python - 将 DataFrame 中的 pandas 系列从字符串(金融缩写)转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48873064/

相关文章:

python - “图像”对象没有属性 '_committed'

python - 如何将 pandas 中的数据框行排序为从一月到十二月的月份

python - Pandas 在夜间重新采样

python - 计算 Pandas 系列变化的表达式过于复杂

python - Raspberry Pi、tkinter、触发器上的屏幕计数器、图像问题

python - 并行Python全局名称错误

python - 如何使用 while 循环使 python 中的 turtle 对象再次出现和消失?

python - 如何在 Python 中获取特定日期范围内的数据?

python - Flask 上下文(应用程序和请求)与线程局部变量

python - 简单游戏的碰撞检测/物理