【问题标题】:Fixing a TypeError when using pandas after replacing a string with a floating point number to eventually generate a bar graph of monthly total precip?在用浮点数替换字符串以最终生成每月总沉淀的条形图后使用 pandas 时修复 TypeError?
【发布时间】:2018-03-08 03:15:29
【问题描述】:

我是 python 和使用 pandas 的新手,在将字符串“T”更改为每日降水列中 0.005 英寸的雨后,我需要帮助创建条形图。以下是一些示例 csv 数据:

Date        HighT  Avgt   LowT   Precip
2017-01-01  46     35     24     T
2017-01-02  54     48     41     0
2017-01-03  54     45     34     0.33
2017-01-04  30     24     19     0.36

csv 文件是 2017 年的每日天气数据。我有每日降水量,并使用 pandas 将“T”(表示微量)替换为 0.005。我从 csv 文件转换了日期以用作我的索引。

%matplotlib inline
import pandas as pd
import numpy as np
import csv
import matplotlib.pyplot as plt

wt = pd.read_csv('CSV/2017-weather.csv')

wt['Date'] = pd.to_datetime(wt['Date'], format = '%m/%d/%y')
wt.index = wt['Date'] 
del wt['Date']

wt.loc[wt['Precip']=='T', ['Precip']] = 0.005

为了绘制条形图,我首先尝试了这个:

wt.groupby(wt.index.month)['Precip'].sum().plot(kind='bar')

但是,我不断收到 TypeError 提示:“无法将 'float' 对象隐式转换为 str。”

然后我尝试将“Precip”列作为自己的数据框,将其转换为所有浮点数,然后再次尝试制作条形图:

wt2 = wt[['Precip']]

wt2.astype(float)

wt2.groupby(wt2.index.month)['Precip'].sum().plot(kind='bar')

我仍然遇到上面提到的相同错误,目前我不确定如何解决该错误。

任何帮助将不胜感激!

【问题讨论】:

  • 您介意发布几行简化的 csv 或数据框吗?

标签: python python-3.x pandas


【解决方案1】:

如果您查看您提供的数据中的第一行数据,您可以看到Precip 的值是"T"。由于这不是数字,因此无法转换为float,因此会抛出TypeError

尝试删除第一行,您的代码应该可以工作。

【讨论】:

  • 作为我们任务的一部分,我们必须将“T”(表示跟踪量)替换为浮点数 0.005。我使用了代码: wt.loc[wt['Precip']=='T', ['Precip']] = 0.005 这样做。将 T 转换为浮点数并将其他值转换为浮点数后仍然出现错误。
猜你喜欢
  • 2020-04-13
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
相关资源
最近更新 更多