Pandas如何基于列条件判断为DataFrame新增符合要求的行
Pandas 数据处理实现方案
前置依赖
确保beg、end列已转换为pandas datetime类型。
实现代码
import pandas as pd from datetime import time # 1. 构造示例输入数据 df = pd.DataFrame({ 'id': ['guest1', 'guest2'], 'beg': pd.to_datetime(['2021-10-21 17:00:00', '2021-10-21 10:00:00']), 'end': pd.to_datetime(['2021-10-21 18:00:00', '2021-10-22 10:00:00']) }) # 2. 筛选仅出现1次的客户id id_count = df['id'].value_counts() single_occur_ids = id_count[id_count == 1].index process_df = df[df['id'].isin(single_occur_ids)].reset_index(drop=True) result_list = [] for _, row in process_df.iterrows(): beg_date = row['beg'].date() end_date = row['end'].date() # 情况1:beg和end为同一天 if beg_date == end_date: # 新增行 new_row = row.copy() new_row['col1'] = pd.Timestamp.combine(beg_date, time(0,0,0)) new_row['col2'] = row['beg'] result_list.append(new_row) # 原有行更新字段 original_row = row.copy() original_row['col1'] = row['end'] original_row['col2'] = pd.Timestamp.combine(beg_date, time(23,59,59)) result_list.append(original_row) # 情况2:beg和end不为同一天 else: update_row = row.copy() update_row['col1'] = pd.Timestamp.combine(beg_date, time(0,0,0)) update_row['col2'] = row['beg'] result_list.append(update_row) # 3. 转换为最终DataFrame final_df = pd.DataFrame(result_list).reset_index(drop=True) # 可选:格式化时间为字符串,和示例输出格式完全一致 time_cols = ['beg', 'end', 'col1', 'col2'] final_df[time_cols] = final_df[time_cols].apply(lambda x: x.dt.strftime('%Y-%m-%d %H:%M:%S')) print(final_df)
输出结果
运行代码后得到的final_df和需求要求的输出完全匹配:
| id | beg | end | col1 | col2 |
|---|---|---|---|---|
| guest1 | 2021-10-21 17:00:00 | 2021-10-21 18:00:00 | 2021-10-21 00:00:00 | 2021-10-21 17:00:00 |
| guest1 | 2021-10-21 17:00:00 | 2021-10-21 18:00:00 | 2021-10-21 18:00:00 | 2021-10-21 23:59:59 |
| guest2 | 2021-10-21 10:00:00 | 2021-10-22 10:00:00 | 2021-10-21 00:00:00 | 2021-10-21 10:00:00 |
内容的提问来源于stack exchange,提问作者dsp
相关产品推荐
相关产品推荐

