我有一个由类别和文本字符串组成的数据框:
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())
它有正确的键,但每一个键都会一遍又一遍地给我该类别第一行的单词。所以我有一本字典,上面有一个列表,上面写着猫狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗狗。你知道吗
这应该够了
额外学分 获取唯一列表
优等生
value_counts
因为我觉得这很有趣您可以先设置索引,然后对索引进行拆分,然后对索引进行分组,并用
sum
连接所有列表,并用它生成一个dict。你知道吗输出
相关问题 更多 >
编程相关推荐