Skip to main content
 首页 » 编程设计

python之从字符串中提取字符并在 Python 中形成新列

2025年05月04日25soundcode

我有一个像这样的 Pandas DataFrame :

      Date                   Descriptive           
0  2017-1-1    Time12:30 Id124562 American electronic commerce and cloud computing company based in Seattle      
1  2017-1-2    Time12:40 Id124565 Amazon has separate retail websites for the United States 
2  2017-1-3    Time12:45 Id124561 In 2020, Amazon will build a new downtown Seattle building  

如何使用 Python 生成这样的新 DataFrame?

         Date        time      id           descriptive 
    0  2017-1-1     12:30    124562     American electronic commerce and cloud computing company based in Seattle      
    1  2017-1-2     12:40    124565     Amazon has separate retail websites for the United States 
    2  2017-1-3     12:45    124561     In 2020, Amazon will build a new downtown Seattle building  

PS:抱歉,我制作这个数据框是为了代表我遇到的真实数据清理问题。 id的长度固定为6。非常感谢。

请您参考如下方法:

join 与 split 使用 expand=True

cols = ['Time', 'Type', 'Price', 'Id'] 
 
df.join( 
    pd.DataFrame( 
        df.Descriptive.str.replace( 
            r'(?:{})([^\s]+)'.format('|'.join(cols)), 
            r'\1' 
            ).str.split(expand=True).values, 
            columns = cols 
        ) 
) 
 
# Result 
 
       Date                            Descriptive   Time Type Price        Id 
0  2017-1-1    Time12:30 Type021 Price11$ Id124562  12:30  021   11$    124562 
1  2017-1-2  Time12:40 Type011 Price11$ Id12456512  12:40  011   11$  12456512 
2  2017-1-3  Time12:45 Type031 Price11$ Id12456125  12:45  031   11$  12456125