使用字典迭代列列表

nwlls2ji  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(368)

我在数据框中有一个列表:

0: [car, telephone]
1: [computer, beach, book, language]
2: [rice, bus, street]

每个列表都在每一行中。此外,此列表在每一行中都有不同的长度。我有一本字典:

dict = {'car': 'transport',
'rice':'food'
'book':'reading'
}

在那之后,我把听写纸弄平了

d = {val:key for key, lst in dict.items() for val in lst}

我想迭代列表中的所有项目,并创建一个此类列,
这是所需的输出:

index col1  col2
    0: [car, telephone],transport
    1: [computer, beach, book, language], reading
    2: [rice, bus, street], food

我试过:

df['col2'] = data_df['col1'].index.map(d)

但我明白了

col2
NaN
NaN
NaN
ltskdhd1

ltskdhd11#

你可以 .explode 然后使用字典进行翻译,然后再次分组:
样本数据:

import pandas as pd
data = {'id': {0: 1, 1: 2, 2: 3}, 'col': {0: ['car', 'telephone'], 1: ['computer', 'beach', 'book', 'language'], 2: ['rice', 'bus', 'street']}}
df = pd.DataFrame(data)

dct = {'car': 'transport', 'rice':'food', 'book':'reading'}

代码:

df2 = df.explode('col')
df2['col2'] = df2['col'].replace(dct)
df['col2'] = df2[~df2['col'].eq(df2['col2'])]['col2']

输出:

id                                col       col2
0   1                   [car, telephone]  transport
1   2  [computer, beach, book, language]    reading
2   3                [rice, bus, street]       food
5sxhfpxr

5sxhfpxr2#

你可以用 apply 在自定义函数上:

import pandas as pd

df = pd.DataFrame([{'col1': ['car', 'telephone']}, {'col1': ['computer', 'beach', 'book', 'language']}, {'col1': ['rice', 'bus', 'street']}])

def get_col2(lst):
    d={'car': 'transport','rice':'food','book':'reading'}
    for k,v in d.items():
        if k in lst:
            return v

df['col2'] = df['col1'].apply(get_col2)

输出:
COL20[汽车、电话]交通1[计算机、海滩、书籍、语言]阅读2[大米、公共汽车、街道]食物

相关问题