【问题标题】:Pandas dataframe, ValueError: shape mismatch: objects cannot be broadcast to a single shapePandas 数据框,ValueError:形状不匹配:无法将对象广播到单个形状
【发布时间】:2019-02-16 07:53:17
【问题描述】:

我有这个代码,用于跟踪特定交货的延迟时间以及交货时间。我将它们分类为:提前交货、准时交货和延迟交货。如果我包括每个材料编号,我可以绘制这些结果。但是,当我按材料编号指定时,我遇到了一个错误(如下所列),我还提供了终端中准确打印的内容。似乎数据框创建了两行标记不同的东西,并且从那里开始计数,因此我无法绘制图表,因为有两个值,那么我该如何修复我的代码以简单地提取“计数”并使用该数字绘制条形图

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd


Material= 'Material'
DELIVERY_DATE = 'Delivery Date'
DESIRED_DATE = 'source desired delivery date'
DELAYED_DAYS = 'Delayed Days'



StartYear = input("Start Year? ")
StartYear = int(StartYear)
EndYear = input("End Year? ")
EndYear = int(EndYear) 




DELIVERY_DATE = 'Delivery Date'
DESIRED_DATE = 'source desired delivery date'
DELAYED_DAYS = 'Delayed Days'


df = pd.read_csv('otdo.csv')

df['Delivery Date'] = pd.to_datetime(df['Delivery Date'], format='%m/%d/%Y')
df['source desired delivery date'] = pd.to_datetime(df['source desired delivery date'], format='%m/%d/%Y')


late_threshold = pd.Timedelta(days=0)
late_threshold2 = pd.Timedelta(days=10)

df[DELIVERY_DATE] = pd.to_datetime(df[DELIVERY_DATE])
df[DESIRED_DATE] = pd.to_datetime(df[DESIRED_DATE])
df[DELAYED_DAYS] = df[DELIVERY_DATE] - df[DESIRED_DATE]


df2 = df[(df['Delivery Date'].dt.year >= int(StartYear)) & (df['Delivery Date'].dt.year <= int(EndYear))]



df3 = df2[ df2[DELAYED_DAYS] > late_threshold] 
df3 =  df3[late_threshold2 > df3[DELAYED_DAYS]]
df3 = df3.loc[df['Material'].str.contains('20080810', na=False)]




df4 = df2[ df2[DELAYED_DAYS] > late_threshold2] 
df4 = df4.loc[df['Material'].str.contains('20080810', na=False)]


df5 = df2[df2[DELAYED_DAYS] <= late_threshold] 
df5 = df5.loc[df['Material'].str.contains('20080810', na=False)]


df6 = df2.loc[df['Material'].str.contains('20080810', na=False)]




df7 = df2[ df2[DELAYED_DAYS] > late_threshold] 
df7 =  df7[late_threshold2 > df7[DELAYED_DAYS]]



df8 = df2[ df2[DELAYED_DAYS] > late_threshold2] 


df9 = df2[df2[DELAYED_DAYS] <= late_threshold] 


zero = df2.count() 
zero2 = df3.count()
zero3 = df4.count() 
zero4 = df5.count() 
zero5 = df7.count()
zero7 = df9.count() 

hey = zero7.iloc[1:1]
print(hey)
print(zero7)

objects = ('1', '2', '3')
y_pos = np.arange(len(objects))
values = [zero5, zero4, zero7]

plt.bar(y_pos, values, align='center', alpha=0.2)
plt.xticks(y_pos, objects)

plt.show()

这是在终端中生成的:

Start Year? 2014
End Year? 2018
Series([], dtype: int64)
Material        4936
Delayed Days    4936
dtype: int64
Traceback (most recent call last):
  File "C:\Users\khalha\eclipse-workspace\Test3\Test3\gagada.py", line 118, in <module>
    plt.bar(y_pos, values, align='center', alpha=0.2)
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\pyplot.py", line 2770, in bar
    ret = ax.bar(*args, **kwargs)
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\__init__.py", line 1855, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\axes\_axes.py", line 2233, in bar
    np.atleast_1d(x), height, width, y, linewidth)
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\stride_tricks.py", line 249, in broadcast_arrays
    shape = _broadcast_shape(*args)
  File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\stride_tricks.py", line 184, in _broadcast_shape
    b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape

CSV 文件:

Material    Delivery Date   source desired delivery date
3334678 12/31/2014  12/31/2014
233433  12/31/2014  12/31/2014
3434343 1/5/2015    1/5/2015
3334567 1/5/2015    1/6/2015
546456  2/11/2015   2/21/2015
221295  4/10/2015   4/10/2015

【问题讨论】:

    标签: python pandas csv datetime matplotlib


    【解决方案1】:

    错误信息说在

    plt.bar(y_pos, values...
    

    matplotlib 期望条形高度为一维数组,但使用values,您提供了一个数据帧列表,无法将其广播到简单的一维数组。

    您应该改用标量列表来完成这项工作。

    例如

    values = [zero5.Material, zero4.Material, zero7.Material]
    

    如果我理解您的数据模型是正确的。
    请注意,如果您想绘制两个数组,即每个 y_pos 上的两个条形图,可以通过调用 plt.bar(...) 两次来完成。首先使用一个数组,然后使用另一个数组,将一些 y 偏移添加到 y-pos 数组。示例见this

    但是 - 我建议您不要创建太多从 csv-import 派生的进一步数据帧,而是创建一个单独的数据帧,其中包含取决于您的阈值时间的布尔结果,大概已经转换为“int”以计算总和,例如:

    df2['thresh1'] = (df2[DELAYED_DAYS] > late_threshold).astype(int)
    df2['thresh2'] = (df2[DELAYED_DAYS] > late_threshold).astype(int)
    

    这让您有机会在一行中计算

    zeros = df2.sum()
    

    你叫什么zeros
    那么第一个测试可能是

    zeros.plot(kind='bar')
    

    【讨论】:

    • 完美运行!非常感谢
    • 不客气。但是,我认为您从 csv 到 plot 的路径是可优化的。我当然不确定我是否理解您的数据和您的任务是否完全正确,但我会尝试在进一步的编辑中为您提供一些额外的提示。
    猜你喜欢
    • 2013-06-01
    • 1970-01-01
    • 2021-05-22
    • 2021-05-13
    • 2021-02-27
    • 1970-01-01
    • 2020-04-28
    • 2021-07-17
    相关资源
    最近更新 更多