pandas 使用Plotly Express创建交互式条形图时出错

4zcjmb1e  于 2023-09-29  发布在  其他
关注(0)|答案(1)|浏览(114)

我尝试使用Plotly Express创建一个交互式条形图,以便按标题显示同一天开始和结束的任务数量。但是,我遇到了一个似乎无法解决的错误。下面是我的代码和示例数据的简化版本:

import plotly.express as px
import pandas as pd

# Sample task data
task_data = {
    'Task Title': ['Task 1', 'Task 2', 'Task 3', 'Task 4'],
    'Start Date': ['2023-09-16', '2023-09-16', '2023-09-17', '2023-09-18'],
    'End Date': ['2023-09-16', '2023-09-17', '2023-09-17', '2023-09-18'],
}

# Create a DataFrame
task_df = pd.DataFrame(task_data)

# Count the occurrences of each task title
task_counts = task_df['Task Title'].value_counts()

# Create an interactive bar chart
fig_task = px.bar(
    task_counts.reset_index(),
    x='index',  # Error occurs here
    y='Task Title',
    labels={'index': 'Task Title', 'Task Title': 'Count'},
    title='Tasks Starting and Ending on the Same Day by Title'
)

# Show the interactive bar chart
fig_task.show()

我收到的错误消息是:

ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of ['Task Title', 'count'] but received: index
To use the index, pass it in directly as `df.index`.
nfg76nw0

nfg76nw01#

错误消息告诉您,在DataFrame task_counts.reset_index()中找不到您尝试使用的“x”列的名称('index')。在pandas Series上重置索引时,新列的默认名称为'index'。但是,由于task_counts是一个Series而不是DataFrame,这意味着重置索引后的列名分配可能与预期不同,因此会出现问题。

import plotly.express as px
import pandas as pd

task_data = {
    'Task Title': ['Task 1', 'Task 2', 'Task 3', 'Task 4'],
    'Start Date': ['2023-09-16', '2023-09-16', '2023-09-17', '2023-09-18'],
    'End Date': ['2023-09-16', '2023-09-17', '2023-09-17', '2023-09-18'],
}

task_df = pd.DataFrame(task_data)

# Filter tasks that start and end on the same day
task_same_day = task_df[task_df['Start Date'] == task_df['End Date']]

# Count the occurrences of each task title for tasks that start and end on the same day
task_counts = task_same_day['Task Title'].value_counts()

# Reset the index and rename the columns
task_counts_df = task_counts.reset_index().rename(columns={'index': 'Task Title', 'Task Title': 'Count'})

# Create your interactive bar chart
fig_task = px.bar(
    task_counts_df,
    x='Task Title',
    y='Count',
    labels={'Task Title': 'Task Title', 'Count': 'Count'},
    title='Tasks Starting and Ending on the Same Day by Title'
)

# Show your interactive bar chart
fig_task.show()

相关问题