【问题标题】:Converting string in a Pandas data frame to float将 Pandas 数据框中的字符串转换为浮点数
【发布时间】:2021-06-06 16:32:28
【问题描述】:

我有以下数据框:

Bestand = pd.DataFrame({'ISIN': ['NaN', 'IE00B4X9L533', 'IE00BF4RFH31'],
                'Marktwert': ['217.803,37', '47.755,10', '15.353,32']})

为了使用名为“Marktwert”的第二列进行计算,我必须将字符串转换为浮点数,字符串具有德语格式,这意味着小数点是逗号,千位分隔符是点。数字 217.803,37 具有数据类型对象。

如果我尝试使用代码进行转换

Bestand['Marktwert'] = pd.to_numeric(Bestand['Marktwert'], downcast="float")

我得到了错误

ValueError: Unable to parse string "217.803,37" at position 0

谁能帮帮我?

【问题讨论】:

  • Bestand.Marktwert.str.replace('.', '').str.replace(',','.').astype(float)
  • ISIN 和 Marktwert 的长度不同。尽量使长度相同
  • @Cyttorak Ty 完美运行!

标签: python pandas dataframe dtype


【解决方案1】:

如果您正在从文件中读取数据,很多 Pandas 的文件阅读器(如 pandas.read_csv())都具有 decimal 和 thousands 参数。

【讨论】:

  • Ty,我确实使用了 read_csv(),但我不熟悉它,我可以在这里使用什么参数?这是我目前使用的代码: Bestand = 'Verm�gensaufstellung.csv' Bestand = pd.read_csv(Bestand, sep=';')
  • 根据docs:Bestand = pd.read_csv(Bestand, sep=';', thousands='.', decimal=',')
  • Ty,它还会处理千位分隔符吗,它是德语格式的一个点?
  • 太棒了,完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 2019-07-06
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多