我尝试使用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`.
1条答案
按热度按时间nfg76nw01#
错误消息告诉您,在DataFrame
task_counts.reset_index()
中找不到您尝试使用的“x”列的名称('index'
)。在pandas Series上重置索引时,新列的默认名称为'index'
。但是,由于task_counts
是一个Series而不是DataFrame,这意味着重置索引后的列名分配可能与预期不同,因此会出现问题。