Python Pandas中的文本连接

cclgggtu  于 6个月前  发布在  Python
关注(0)|答案(2)|浏览(78)

我有以下问题:
我尝试将一个文本合并到一个列中:
基本上,我想加入这样的东西“文本1”+“数字提取1列X”+“文本2”+“数字提取2列X”
这不起作用:

df["EINGRUPPIERUNG"]="P",df["PROJEKT[BEZEICHNUNG]"].str.findall(r"\d+")[:][0]," ","Stufe ",df["PROJEKT[BEZEICHNUNG]"].str.findall(r"\d+")[:][1]

字符串
这是我的数字摘录,其他文本基本上是硬编码的。

df["PROJEKT[BEZEICHNUNG]"].str.findall(r"\d+")
0        [8, 4]
1        [8, 5]
2        [8, 5]
3        [8, 4]
4        [7, 4]
          ...  
13441    [9, 3]
13442    [9, 3]
13443    [9, 3]
13444    [9, 3]
13445    [8, 4]
Name: PROJEKT[BEZEICHNUNG], Length: 13446, dtype: object


谢谢你的帮助,迈克。

nkoocmlb

nkoocmlb1#

可以使用str访问器来获取列表中的单个元素:

match = df['PROJEKT[BEZEICHNUNG]'].str.findall(r'\d+')
df['EINGRUPPIERUNG'] = 'P' + match.str[0] + ' Stufe ' + match.str[1]
print(out)

# Output
  PROJEKT[BEZEICHNUNG] EINGRUPPIERUNG
0        blah 8 blah 4     P8 Stufe 4
1        blah 8 blah 5     P8 Stufe 5
2        blah 8 blah 5     P8 Stufe 5

字符串
str.extract

match = df['PROJEKT[BEZEICHNUNG]'].str.extract(r'(\d+).*(\d+)', expand=True)
df['EINGRUPPIERUNG'] = 'P' + match[0] + ' Stufe ' + match[1]


也可以使用replace

>>> df['PROJEKT[BEZEICHNUNG]'].replace(r'.*(\d+).*(\d+).*',
                                       r'P\1 Stufe \2', regex=True)
0    P8 Stufe 4
1    P8 Stufe 5
2    P8 Stufe 5
Name: PROJEKT[BEZEICHNUNG], dtype: object

rmbxnbpk

rmbxnbpk2#

使用Corralien的例子中的例子df,这里是使用str.findall()map()format()的另一种方式:

df['PROJEKT[BEZEICHNUNG]'].str.findall(r'\d+').map('P {0[0]} Stufe {0[1]}'.format)

字符串
输出量:

0    P 8 Stufe 4
1    P 8 Stufe 5
2    P 8 Stufe 5

相关问题