如何在 pandas 中从列表中提取数据作为字符串,并按值选择数据?

我有一个像这样的数据框:


col1              col2

[abc, bcd, dog]   [[.4], [.5], [.9]]

[cat, bcd, def]   [[.9], [.5], [.4]]

列表中的数字col2描述了 中的元素(基于列表索引位置)col1。所以“.4”col2描述了“abc” col1。


col1我想创建 2 个新列,其中一列仅提取中 >= .9 的元素col2,另一列作为col2;中的数字。所以两行都是“.9”。


结果:


col3     col4

[dog]   .9

[cat]   .9

我认为选择从中删除嵌套列表的路线col2就可以了。但这比听起来更难。我已经尝试了一个小时来移除那些指状支架。


尝试:


spec_chars3 = ["[","]"]


for char in spec_chars3: # didn't work, turned everything to nan

    df1['avg_jaro_company_word_scores'] = df1['avg_jaro_company_word_scores'].str.replace(char, '')


df.col2.str.strip('[]') #didn't work b/c the nested list is still in a list, not a string

我什至还没弄清楚如何提取列表索引号并过滤 col1


阿波罗的战车
浏览 102回答 2
2回答

开心每一天1111

根据问题末尾的解释,似乎两列都是str类型,并且需要转换为list类型.applymap与 一起使用ast.literal_eval。如果只有一列是str类型,则使用df[col] = df[col].apply(literal_eval)每列中的数据列表必须使用以下方法提取pandas.DataFrame.explode外部explode将值从列表转换为标量(即[0.4]转换为0.4)。一旦值位于不同的行上,就可以使用布尔索引来选择所需范围内的数据。如果您想df与结合使用df_new,请使用df.join(df_new, rsuffix='_extracted')测试于python 3.10,pandas 1.4.3import pandas as pdfrom ast import literal_eval# setup the test data: this data is lists# data = {'c1': [['abc', 'bcd', 'dog'], ['cat', 'bcd', 'def']], 'c2': [[[.4], [.5], [.9]], [[.9], [.5], [.4]]]}# setup the test data: this data is stringsdata = {'c1': ["['abc', 'bcd', 'dog', 'cat']", "['cat', 'bcd', 'def']"], 'c2': ["[[.4], [.5], [.9], [1.0]]", "[[.9], [.5], [.4]]"]}# create the dataframedf = pd.DataFrame(data)# the description leads me to think the data is columns of strings, not lists# convert the columns from string type to list type# the following line is only required if the columns are stringsdf = df.applymap(literal_eval)# explode the lists in each column, and the explode the remaining lists in 'c2'df_new = df.explode(['c1', 'c2'], ignore_index=True).explode('c2')# use Boolean Indexing to select the desired datadf_new = df_new[df_new['c2'] >= 0.9]# display(df_new)    c1   c22  dog  0.93  cat  1.04  cat  0.9

慕村9548890

您可以使用列表推导式根据您的条件填充新列。df['col3'] = [    [value for value, score in zip(c1, c2) if score[0] >= 0.9]    for c1, c2 in zip(df['col1'], df['col2'])]df['col4'] = [    [score[0] for score in c2 if score[0] >= 0.9]    for c2 in df['col2']输出              col1                   col2   col3   col40  [abc, bcd, dog]  [[0.4], [0.5], [0.9]]  [dog]  [0.9]1  [cat, bcd, def]  [[0.9], [0.5], [0.4]]  [cat]  [0.9]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python