基于列类别从数据框中的行创建文本列表

2024-04-25 15:28:42 发布

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

我有一个由类别和文本字符串组成的数据框:

category    strings

pets        leash cat dog
pets        cat dog frog
candy       chocolate frog
candy       jelly beans lollipops

我想要两张单子:

petlist = ['leash', 'cat', 'dog', 'cat', 'dog', 'frog']
candylist = ['chocolate', 'frog', 'jelly', 'beans', 'lollipops']

下面的代码列出了strings列中的所有单词:

all_words = df['strings'].str.cat(sep=' ').split()

我怎样才能根据类别将其分成两个列表,并将这两个列表放入词典中?你知道吗

以下是我尝试的:

all_words = {}
for cata in df['category']:
    all_words['wordlist_%s'% cata]=[]
for cata in df['category']:
    df_cata = df.loc[df['category'] == cata]
    all_words['wordlist_%s'% cata].append(df_cata['strings'].str.cat(sep=' ').split())

它有正确的键,但每一个键都会一遍又一遍地给我该类别第一行的单词。所以我有一本字典,上面有一个列表,上面写着猫狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗。你知道吗


Tags: df列表all类别cat狗狗wordsdog
2条回答

这应该够了

df.groupby('category').strings.apply(' '.join).str.split()

category
candy    [chocolate, frog, jelly, beans, lollipops]
pets              [leash, cat, dog, cat, dog, frog]
Name: strings, dtype: object

额外学分 获取唯一列表

df.groupby('category').strings.apply(' '.join).str.split().apply(np.unique)

category
candy    [beans, chocolate, frog, jelly, lollipops]
pets                        [cat, dog, frog, leash]
Name: strings, dtype: object

优等生 value_counts因为我觉得这很有趣

df.groupby('category').strings.apply(' '.join).str.split(expand=True) \
    .stack().groupby(level=0).apply(pd.value_counts)

 category           
candy     jelly        1
          frog         1
          lollipops    1
          beans        1
          chocolate    1
pets      cat          2
          dog          2
          leash        1
          frog         1
dtype: int64

您可以先设置索引,然后对索引进行拆分,然后对索引进行分组,并用sum连接所有列表,并用它生成一个dict。你知道吗

df.set_index('category').strings.str.split().groupby(level='category').sum().to_dict()

输出

{'candy': ['chocolate', 'frog', 'jelly', 'beans', 'lollipops'],
 'pets': ['leash', 'cat', 'dog', 'cat', 'dog', 'frog']}

相关问题 更多 >