You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按分组调整Pandas DataFrame:实现按日期、活动分组并合并时间列

Solution for Reshaping Pandas DataFrame

Got it, let's walk through how to transform your DataFrame into the exact format you need. Here's a step-by-step approach using Pandas:

Step 1: Prepare the Data (or Use Your Existing DataFrame)

First, let's replicate your original DataFrame (skip this if you already have your data loaded):

import pandas as pd

# Create the original DataFrame
data = {
    'activity': ['Phone', 'Phone', 'Coffee', 'Lunch', 'Phone', 'Phone', 'Lunch', 'Lunch',
                 'Phone', 'Pooping', 'Coffee', 'Lunch', 'Phone', 'Meeting', 'Lunch', 'Lunch'],
    'time': ['04:00', '08:30', '10:30', '04:00', '10:30', '04:00', '08:30', '10:30',
             '08:45', '08:50', '10:30', '04:00', '10:30', '04:00', '08:30', '10:30'],
    'date': ['20210810']*8 + ['20210811']*8
}

df = pd.DataFrame(data)

Step 2: Group and Aggregate the Data

We'll group the data by date and activity, then merge all corresponding time values into a single space-separated string:

# Sort the DataFrame first to ensure order matches your target
df_sorted = df.sort_values(['date', 'activity'])

# Group by date and activity, join times with spaces
grouped_df = df_sorted.groupby(['date', 'activity'])['time'].agg(' '.join).reset_index()

Step 3: Format the Output for Readability

To get the "single date per group" and indented activity look, we'll replace duplicate date values with empty strings, then format the print output:

# Replace duplicate dates with empty strings
grouped_df['date'] = grouped_df['date'].mask(grouped_df['date'].duplicated(), '')

# Print in the desired format
print("date activity time")
for _, row in grouped_df.iterrows():
    # Use spaces to indent activities under the same date
    date_display = row['date'] if row['date'] else '          '
    print(f"{date_display} {row['activity']} {row['time']}")

Output Result

Running this code will produce exactly the format you requested:

date activity time
20210810 Coffee 10:30
          Lunch 04:00 08:30 10:30
          Phone 04:00 08:30 10:30 04:00
20210811 Coffee 10:30
          Lunch 04:00 08:30 10:30
          Meeting 04:00
          Phone 08:45 10:30
          Pooping 08:50

Quick Notes

  • The sort_values step ensures the data is ordered by date and activity, matching your target structure.
  • If you prefer a different separator for times (like commas), just swap the string inside ' '.join to ', '.join.
  • The mask/duplicated trick handles hiding repeated dates, and the print formatting adds clean indentation for readability.

内容的提问来源于stack exchange,提问作者Mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:52:30