如何将DataFrame单列中的不同数据拆分至对应列?
解决方法
步骤1:拆分键值对
由于Date/Time字段的时间部分包含冒号,直接用冒号做分隔符会拆分失败,我们需要只拆分字符串中的第一个冒号,分离出每个条目的键(如Place、Date/Time)和对应的值。同时清理值里的多余空格:
import pandas as pd # 原始数据 df = pd.DataFrame( ['Place: House','Date/Time: 01/02/03 at 09:30', 'Color:Yellow', 'Place: Street','Date/Time: 21/12/13 at 13:21:21', 'Color:Red'], columns=['raw'] ) # 拆分第一个冒号,得到key和value列 df[['key', 'value']] = df['raw'].str.split(':', n=1, expand=True) # 去除值里的首尾空格 df['value'] = df['value'].str.strip()
步骤2:分组重组为结构化DataFrame
观察数据可知,每3条记录对应一组完整的信息(Place、Date/Time、Color各一条),我们可以用索引//3生成组号,再通过pivot把每组的键转为列、值转为对应单元格内容:
# 生成组号,每3条为一组 df['group'] = df.index // 3 # 重组为目标结构的DataFrame structured_df = df.pivot(index='group', columns='key', values='value').reset_index(drop=True)
步骤3:清理Date/Time字段(保留日期,去除时间)
如果不需要时间部分,可以通过拆分at关键字提取日期内容:
# 提取at之前的日期部分,丢弃时间 structured_df['Date/Time'] = structured_df['Date/Time'].str.split(' at ', n=1, expand=True)[0]
完整代码与输出
整合所有步骤的代码如下:
import pandas as pd # 原始数据 df = pd.DataFrame( ['Place: House','Date/Time: 01/02/03 at 09:30', 'Color:Yellow', 'Place: Street','Date/Time: 21/12/13 at 13:21:21', 'Color:Red'], columns=['raw'] ) # 拆分键值对 df[['key', 'value']] = df['raw'].str.split(':', n=1, expand=True) df['value'] = df['value'].str.strip() # 分组重组 df['group'] = df.index // 3 structured_df = df.pivot(index='group', columns='key', values='value').reset_index(drop=True) # 清理日期字段 structured_df['Date/Time'] = structured_df['Date/Time'].str.split(' at ', n=1, expand=True)[0] print(structured_df)
运行后输出结果:
Color Date/Time Place 0 Yellow 01/02/03 House 1 Red 21/12/13 Street
内容的提问来源于stack exchange,提问作者Bruno S
相关产品推荐
相关产品推荐

