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

如何在Python中从字符串提取字符并为Pandas DataFrame生成新列

解决Pandas数据拆分与列重命名的问题

没问题,咱们来搞定这个数据清洗的需求!首先我先把原DataFrame的结构理清楚——看起来你的原始数据里,Date列其实是把日期、带Time前缀的时间、带Id前缀的ID这三个信息合并在一起了,而Descriptive列是对应的描述文本。我们需要把这些拆分出来,再整理成目标格式。

步骤1:构造原始DataFrame(还原你的输入数据)

首先先把你给出的模拟数据转换成Pandas DataFrame,方便后续操作:

import pandas as pd

# 原始数据
data = {
    'Date': [
        '2017-1-1 Time12:30 Id124562',
        '2017-1-2 Time12:40 Id124565',
        '2017-1-3 Time12:45 Id124561'
    ],
    'Descriptive': [
        'American electronic commerce and cloud computing company based in Seattle',
        'Amazon has separate retail websites for the United States',
        'In 2020, Amazon will build a new downtown Seattle building'
    ]
}
df = pd.DataFrame(data)

步骤2:拆分Date列并提取关键信息

我们可以用str.split()把Date列按空格拆分成三个部分,然后分别提取日期、时间、ID:

# 拆分Date列为三个部分:日期、带前缀的时间、带前缀的ID
split_date = df['Date'].str.split(' ', expand=True)
split_date.columns = ['Date', 'time_raw', 'id_raw']

# 处理时间:去掉前缀"Time"
split_date['time'] = split_date['time_raw'].str.replace('Time', '')

# 处理ID:去掉前缀"Id"(因为ID长度固定6位,也可以用切片:.str[-6:])
split_date['id'] = split_date['id_raw'].str.replace('Id', '')

步骤3:合并数据并整理成目标格式

把处理后的列和原有的Descriptive列合并,然后调整列顺序、重命名列:

# 合并数据
result_df = pd.concat([split_date[['Date', 'time', 'id']], df['Descriptive']], axis=1)

# 重命名Descriptive列为小写的descriptive
result_df.rename(columns={'Descriptive': 'descriptive'}, inplace=True)

最终结果

运行上面的代码后,result_df就是你想要的格式啦:

Date   time      id                                        descriptive
0  2017-1-1  12:30  124562  American electronic commerce and cloud computi...
1  2017-1-2  12:40  124565  Amazon has separate retail websites for the Un...
2  2017-1-3  12:45  124561  In 2020, Amazon will build a new downtown Seat...

补充说明

因为你提到ID长度固定为6位,所以除了用str.replace('Id', ''),也可以用split_date['id_raw'].str[-6:]来提取,这样即使前缀有变化(比如不是"Id"而是其他),也能准确拿到最后6位的ID,灵活性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:56:17