我正在尝试使用 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`.
错误消息告诉您在 DataFrame
'index'
中找不到您尝试使用的“x”列的名称 (task_counts.reset_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()