【问题标题】:Python and pandas: Convert a column in CSV file to integerPython 和 pandas:将 CSV 文件中的列转换为整数
【发布时间】:2021-01-06 07:40:33
【问题描述】:

我的要求是读取包含以下列的 csv 文件:日期、最高温度 (TMAX)、最低温度 (TMIN) 稍后我需要按季度汇总并绘制条形图。

我正在使用下面的代码,但它不起作用。

#importing necessary libraries
import pandas as pd
import matplotlib.pyplot as plt

#Reading the file using pandas
df = pd.read_csv(r"C:\Users\home\Downloads\2285297.csv", parse_dates = ['DATE'])

# Reading each column
np_maxtemp= df.loc[:,['TMAX']]
np_mintemp= df.loc[:,['TMIN']]
np_date= df.loc[:,['DATE']]

#Summarizing Max temp by each quarter
df['np_quarter'] = pd.PeriodIndex(df.DATE, freq='Q')
#It gives me list of all quarters 0 2010Q1   1 2010Q2

avg_tmax=df.groupby(by=['np_quarter'])['TMAX'].mean()
avg_tmin=df.groupby(by=['np_quarter'])['TMIN'].mean()
#It gives me averages by quarter


# Then I want to plot with quarters on x-axis and temperature bar plots on y-axis
plt.plot(df['np_quarter'])
plt.ylabel(avg_prec)
plt.show()

第一行本身报错:TypeError: float() argument must be a string or a number, not 'Period'

如何将这些四分之一转换为字符串并在 y 轴上绘制平均温度?

数据

   STATION       DATE  PRCP  TMAX  TMIN np_quarter
0   USW00012921 2010-12-01   0.0  65.0  29.0     2010Q4
1   USW00012921 2010-12-02   0.0  71.0  37.0     2010Q4
2   USW00012921 2010-12-03   0.0  76.0  44.0     2010Q4
3   USW00012921 2010-12-04   0.0  79.0  55.0     2010Q4
4   USW00012921 2010-12-05   0.0  60.0  41.0     2010Q4
5   USW00012921 2010-12-06   0.0  59.0  36.0     2010Q4
6   USW00012921 2010-12-07   0.0  60.0  36.0     2010Q4
7   USW00012921 2010-12-08   0.0  60.0  37.0     2010Q4
8   USW00012921 2010-12-09   0.0  65.0  31.0     2010Q4
9   USW00012921 2010-12-10   0.0  74.0  39.0     2010Q4
10  USW00012921 2010-12-11   0.0  75.0  43.0     2010Q4
11  USW00012921 2010-12-12   0.0  60.0  34.0     2010Q4
12  USW00012921 2010-12-13   0.0  60.0  29.0     2010Q4
13  USW00012921 2010-12-14   0.0  72.0  38.0     2010Q4
14  USW00012921 2010-12-15   0.0  76.0  46.0     2010Q4
15  USW00012921 2010-12-16   0.0  64.0  48.0     2010Q4
16  USW00012921 2010-12-17   0.0  57.0  41.0     2010Q4
17  USW00012921 2010-12-18   0.0  58.0  34.0     2010Q4
18  USW00012921 2010-12-19   0.0  67.0  34.0     2010Q4
19  USW00012921 2010-12-20   0.0  76.0  48.0     2010Q4

【问题讨论】:

  • 第一行?导入还是 read_csv?我无法用当前信息复制您的问题。

标签: python pandas plot


【解决方案1】:

我认为加载文件时存在问题,因为它是用空格而不是逗号分隔的。我不确定你想要绘制什么,但这里是每个季度的平均值(最小值和最大值)。我还按照 PEP8 中的建议在运算符周围放置空格以提高可读性。如果它不起作用,请告诉我。

#Reading the file using pandas
df = pd.read_csv(r"C:\Users\home\Download\2285297.csv", delim_whitespace=True)  # delimiter is whitespace not comma
df['DATE'] = pd.to_datetime(df['DATE'])

# Reading each column
np_maxtemp = df.loc[:, ['TMAX']]
np_mintemp = df.loc[:, ['TMIN']]
np_date = df.loc[:, ['DATE']]

#Summarizing Max temp by each quarter
df['np_quarter'] = pd.PeriodIndex(df.DATE, freq='Q')
#It gives me list of all quarters 0 2010Q1   1 2010Q2

avg_tmax = df.groupby(by=['np_quarter'])['TMAX'].mean()
avg_tmin = df.groupby(by=['np_quarter'])['TMIN'].mean()
#It gives me averages by quarter

# Then I want to plot with quarters on x-axis and temperature bar plots on y-axis
plt.plot([str(avg_tmax.index[0]) + " MAX",
          str(avg_tmax.index[0]) + " MIN"],
         [avg_tmax[0], avg_tmin[0]],
         'o')
plt.ylabel('avg_prec')  # change to str
plt.show()

【讨论】:

  • 当我使用空格分隔符时,我得到以下错误行 np_maxtemp= df.loc[:,['TMAX']]: "Error: KeyError: "None of [Index(['TMAX'] , dtype='object')] 在 [columns]"
  • 你是否也在下面添加了df['DATE'] = pd.to_datetime(df['DATE'])这一行?尝试复制和粘贴整个代码块,以检查它是否完整;目前我无法用上面的代码重现错误。
  • 如果我完全使用代码,我会收到错误:FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\home\\Download\\2285297.csv'。或者如果我将读取文件行修改为:df = pd.read_csv(r"C:\Users\home\Downloads\2285297.csv", delim_whitespace=True),我得到错误:文件“C:\Users\home\ AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\indexes\base.py",第 2893 行,在 get_loc 中从 err KeyError: 'DATE' 引发 KeyError(key)。我正在使用 python 版本 3.8.5
  • 我唯一能想到的另一件事是文件格式存在一些差异,我将您的示例复制并粘贴到记事本中并保存为.csv。可能值得尝试使用您的原始 CSV,因为它对我有用(python 3.7),否则很抱歉我无法提供更多帮助。
猜你喜欢
  • 2015-05-04
  • 1970-01-01
  • 2018-11-24
  • 2013-01-08
  • 2013-08-13
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
相关资源
最近更新 更多