【问题标题】:creating a scatter plot in Python在 Python 中创建散点图
【发布时间】:2020-10-29 13:13:01
【问题描述】:

我正在尝试在 Python 中创建一个plot,并将日期作为我的 x 轴(12/6/2010 格式)。 Picture is attached.

附上我写的代码。我收到一个错误。请帮忙。

import pandas as pd

df1 = pd.read_csv(r"C:\Users\pc237\.spyder-py3\monthly_csv.csv")

df_1 = df1.loc[df1['Source'] == 'GCAG']
df_2 = df1.loc[df1['Source'] == 'GISTEMP']

import matplotlib.pyplot as plt

x1 = df_1['Date'],
y1 = df_1['Mean'],

x1 = [pd.to_datetime(d) for d in x1]

plt.scatter(x1,y1)

错误:

Traceback (most recent call last):
  File "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\pandas\tseries\converter.py", line 213, in convert
    values = tools.to_datetime(values)

【问题讨论】:

  • 我认为这里不需要列表理解,因为您的 x1 已经是 pandas 对象。试试:x1 = pd.to_datetime(x1)
  • 如果这不起作用,请显示更多的回溯'
  • Traceback:File "", line 1, in File "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\pandas\util\decorators.py",第 91 行,在包装器中返回 func(*args, **kwargs) 文件“C:\Software\Eng_APPS\Anaconda3\lib\site-packages\pandas\tseries\tools.py”,第 428 行,在 to_datetime 中返回 _convert_listlike(arg , 框, 格式) 文件 "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\pandas\tseries\tools.py", 第 345 行, in _convert_listlike raise TypeError('arg must be a string, datetime, list, tuple, ' TypeError: arg 必须是字符串、日期时间、列表、元组、一维数组或系列
  • 我也看到了这个错误:return array(a, dtype, copy=False, order=order, subok=True) ValueError: could not convert string to float: '1/6/1880'
  • 也可以试试,在调用 to_datetime 时设置 infer_datetime_format=True

标签: python pandas scatter-plot


【解决方案1】:

我认为这里不需要列表理解,因为您的 x1 已经是 pandas 对象。并且您需要将推断日期时间格式标志设置为 True。

x1 = pd.to_datetime(x1, infer_datetime_format=True)

【讨论】:

  • 回溯(最近一次调用最后一次):文件“”,第 1 行,在 类型错误:arg 必须是字符串、日期时间、列表、元组、一维数组或系列
  • 在调用 to_datetime 之前将 x1 变量的打印输出添加到问题提示中。从您的回溯中,无法判断您尝试将什么转换为日期时间
猜你喜欢
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
相关资源
最近更新 更多