当使用搜索字符串迭代不同的列时,您可以使用 str.cat 连接 Pandas Series 的一些(但不是全部)条目吗?

问题描述 投票:0回答:1

我使用下面的数据和数据框来使用search_string来查询一列/系列,然后当字符串匹配时,更新不同列/系列中的信息。我可以完成它,但不是我想要的方式 - 我想要文本更新之间有空格。我已经用尽了我的搜索和查看文档。我发现的最接近的是 str.cat - 但这似乎只适用于整个系列。我反复收到“ValueError:您是否打算提供

sep
关键字?”

下面显示了注释掉的有效内容(尽管没有空格)以及当前无效的内容。

import pandas as pd
search_str = ['STRAUSS', 'STREET', 'STUBBY\'S']

data = {
  "calories": ['STRAUSS_STREET', 'ten', 'twenty'],
  "duration": [50, 40, 45],
  "test": ['not_yet_set', 'not_yet_set', 'not_yet_set']    
}

df_1 = pd.DataFrame(data)
df_1["calories"] = pd.Series(df_1["calories"], dtype=pd.StringDtype)

for k in range(len(search_str)):
    #df_1.loc[df_1['calories'].str.contains(search_str[k]), 'test'] += search_str[k]
    df_1.loc[df_1['calories'].str.contains(search_str[k]), 'test'] = 
        df_1['test'].str.cat(search_str[k], sep=',', na_rep='-')

df_1
python pandas string series string-concatenation
1个回答
0
投票

IIUC,您可以根据搜索词创建正则表达式,然后使用

str.findall
查找
df_1['calories']
中的所有匹配项。这将生成一个列表,然后您可以使用
join
:
 
map

rgx = '|'.join(search_str)
df_1['test'] = df_1['calories'].str.findall(rgx).map(', '.join)

输出:

         calories  duration             test
0  STRAUSS_STREET        50  STRAUSS, STREET
1             ten        40
2          twenty        45
© www.soinside.com 2019 - 2024. All rights reserved.