如何将Pandas DataFrame的Column B拆分为Information、Price、Place列?
拆分Pandas DataFrame中结构化字符串列的高效方法
核心方案:正则表达式精准提取
利用str.extract结合正则表达式,一次性匹配并提取所有目标字段,是最直接高效的方式:
- 构造示例数据(可直接替换为你的
df):
import pandas as pd data = { 'Column A': ['Item_ID1', 'Item_ID2'], 'Column B': [ 'Information - information for item that has ID as 1\nPrice - $7.99\nPlace - Albany, NY', 'Information - item\'s information with ID as 2\nPrice - $5.99\nPlace - Ottawa, ON' ] } df = pd.DataFrame(data)
- 正则提取与合并:
# 正则表达式匹配每个字段的内容 extracted_cols = df['Column B'].str.extract( r'Information - (.*?)\nPrice - (.*?)\nPlace - (.*)', expand=True ) # 设置提取后的列名 extracted_cols.columns = ['Information', 'Price', 'Place'] # 合并原列与提取结果 result_df = pd.concat([df['Column A'], extracted_cols], axis=1)
执行后result_df就是你需要的结构,正则中的(.*?)是非贪婪匹配,确保只捕获对应标识到下一个换行符之间的内容,不会包含后续字段。
备选方案:拆分后透视(适用于字段数量不固定的场景)
如果后续可能新增其他字段,可通过拆分、透视的方式动态处理:
# 按换行符拆分每行内容,展开为多行 temp = df['Column B'].str.split('\n', expand=True).stack() # 按' - '拆分键值对(n=1避免内容中包含'-'时出错) temp = temp.str.split(' - ', n=1, expand=True) # 重置索引并透视成宽表 temp = ( temp.reset_index(level=1, drop=True) .rename(columns={0: 'key', 1: 'value'}) .pivot(columns='key', values='value') ) # 合并原列得到结果 result_df = pd.concat([df['Column A'], temp], axis=1)
内容的提问来源于stack exchange,提问作者Sanket Sathe
相关产品推荐
相关产品推荐

