使用数据帧列错误:值错误:数据帧的真值不明确。

2024-10-04 01:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在基于数据帧列的散点图中添加一条水平线-我得到以下错误:ValueError:dataframe的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()


x_line = datLong.groupby('ctr1').agg({'maxx': ['mean']})

for country in datLong.ctr1.unique():
    temp_df = plt.figure(country)
    temp_df = datLong[datLong.ctr1 == country]
    ax1 = temp_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label = 'xx', linewidth =3, alpha = 0.7, figsize=(7,4))    
   
    plt.title(country)
    plt.axvline(x=x_line) ### this is the line that is causing this error
 
    plt.show()
print (ax1)

问题似乎与数据帧有关。但我能弄清楚是什么?有人能帮我吗


Tags: 数据dataframedfis错误linepltthis
1条回答
网友
1楼 · 发布于 2024-10-04 01:28:43

x_line包含所有国家/地区的值。使用x_line.loc[country]您将获得该国家的值。因为它返回一个数组(只有一个元素),并且axvline只接受单个值,所以可以选择它的第一个元素(x_line.loc[country][0]

请注意plt.figure会创建一个图形,不带ax=参数的pandas plot也会创建一个新图形。因此,您应该省略plt.figure(),或者显式创建一个ax来绘制

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

datLong = pd.DataFrame({'ctr1': np.repeat(['country 1', 'country 2'], 20),
                        'x': np.tile(np.arange(20), 2),
                        'maxx': np.random.randn(40) + 10,
                        'Price': np.random.randn(40) * 10 + 200})

x_line = datLong.groupby('ctr1').agg({'maxx': ['mean']})

for country in datLong.ctr1.unique():
    temp_df = datLong[datLong.ctr1 == country]
    ax1 = temp_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label='xx', linewidth=3, alpha=0.7,
                       figsize=(7, 4))
    ax1.figure.canvas.set_window_title(country)
    ax1.set_title(country)
    ax1.axvline(x=x_line.loc[country][0])
    plt.show()

由于groupby已经为每个国家创建了数据帧,您可以使用groupby重写代码(无需x_line):

for country, country_df in datLong.groupby('ctr1'):
    ax1 = country_df.plot(kind='scatter', x='x', y='Price', color='#d95f0e', label='xx', linewidth=3, alpha=0.7,
                       figsize=(7, 4))
    ax1.figure.canvas.set_window_title(country)
    ax1.set_title(country)
    ax1.axvline(x=country_df['maxx'].mean())
    plt.show()

相关问题 更多 >