gpt4 book ai didi

python - 通过匹配列表中的字符串值在 Pandas 数据框中构建新列

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:51 24 4
gpt4 key购买 nike

我正在尝试在基于数据框中已有的另一列 SearchCol3 的 pandas 数据框中构建一个新列 NewCol4SearchCol3 的每个值都经过测试,以查看它是否包含列表 stings 中的任何子字符串。如果 SearchCol3 中的值包含列表 strings 中的子字符串之一,则将列表 replacement 中的相应值插入到列中NewCol4 子字符串所在的同一行。如果在 SearchCol3 的值中未找到子字符串,则 Col2 的值> 被插入到 NewCol4 中。

期望的结果:

    Col1  Col2    SearchCol3   NewCol4
0 20 'May' 'abc(feb)' 'February'
1 30 'March' 'def | mar' 'March'
2 40 'June' 'ghi | feb' 'February'
3 50 'July' 'jkl(apr)' 'April'
4 60 'May' 'mno(mar)' 'March'
5 70 'March' 'abc' 'March'

目前我正在使用这个代码来完成这项工作。

strings = ['jan',
'feb',
'mar',
'apr',
'may']

replacement = ['January',
'Febuary',
'March',
'April',
'May']


data = pandas.read_csv('data.csv')

data['NewCol4'] = ''

for j in range(len(strings)):
for i in range(len(data)):
if strings[j] in data.SearchCol3[i]:
data.NewCol4[i] = replacement[j]


for i in range(len(data)):
if data.NewCol4[i] == '':
data.NewCol4[i] = data.Col2[i]

我的数据、搜索和替换数据框和列表比本例中的要长得多。我正在寻找比我目前使用的方法更有效的方法来节省时间。有什么建议吗?

最佳答案

这对我有用,而且从好的方面来说,它非常可读!

strings = ['jan', 'feb', 'mar', 'apr', 'may']
replacement = ['January', 'February', 'March', 'April', 'May']

def match_string(col3, col2):
# if in col3, return that result. Else, lazy eval for col2. If neither, return empty string.
k = ([replacement[strings.index(s)] for s in strings if s in col3]) or ([s for s in replacement if s in col2])
return k[0] if k else ''

df['NewCol4'] = df.apply(lambda x: match_string(x['SearchCol3'], x['Col2']), axis=1)

输出:

    Col2 SearchCol3   NewCol4
0 May abc(feb) February
1 March def | mar March
2 June ghi | feb February
3 July jkl(apr) April
4 May mno(mar) March
5 March abc March

关于python - 通过匹配列表中的字符串值在 Pandas 数据框中构建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com