拆分列表中的不同值,并用逗号分隔

2024-09-28 05:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框

^{tb1}$

这是通过在列上应用.value_counts()来实现的,正如您所看到的,开发人员与其他人的答案结合在一起时是重复的,从这个数据框架中,我想创建一个可能的日志列表,以计算稍后重复的每个日志的数量

我尝试了下面的代码以首先找到唯一的值

unqlist=list(df_new['DevType'].unique())

通过使用“unqlist”,我尝试使用下面的代码来分隔不同的单词

possiblewords=[]
for word in unqlist:
    print(word.split(','))
   possiblewords.append(word)

它不起作用了


Tags: 数据答案代码框架df列表数量开发人员
3条回答

以下是一个例子:

list(set(''.join(filter(lambda x: isinstance(x, str), devtype_list)).split(',')))

您可以使用Pandas^{}在逗号和分号上拆分,将结果放入numpy数组中。然后,使用^{}获得从2D数组展平到1D数组后的唯一字,如下所示:

import numpy as np

list_all = df_new['DevType'].str.split(r'(?:,|;)\s*').dropna().to_numpy()

list_unique = np.unique(sum(list_all, []))

结果:

print(list_unique)

['Devel...' 'Developer' 'back-end' 'desktop or ente...'
 'embedded applications or devices' 'front-end' 'full-stack']

您可以使用,;作为分隔符拆分列表,以分隔唯一的单词

def split_words(x):
    return sum(list(map(lambda y: y.split(";"), x.split(','))), [])

devtype_list = ['Developer, desktop or enterprise applications;Developer, full-stack', 'Developer, full-stack;Developer, mobile', 'nan', 'Designer;Developer, front-end;Developer, mobile', 'Developer, back-end;Developer, front-end;Developer, QA or test;DevOps specialist', 'Developer, back-end;Developer, desktop or enterprise applications;Developer, game or graphics', 'Developer, full-stack', 'Database administrator;']
newlist = list(set(sum(list(map(lambda x: split_words(x), devtype_list)), [])))
newlist = list(map(lambda x: x.strip(), newlist))

for unique_word in newlist:
    print(unique_word)

结果:

Developer
front-end

Designer
desktop or enterprise applications
game or graphics
mobile
Database administrator
QA or test
DevOps specialist
nan
back-end
full-stack

相关问题 更多 >

    热门问题