【问题标题】:Split multi-selection answer to different columns in Excel or Python将多选答案拆分到 Excel 或 Python 中的不同列
【发布时间】:2021-03-17 02:42:36
【问题描述】:

我有一列来自多选多项选择题的答案。像这样:

Answer
Dog, Cat, Bird
Dog, Bird
Dog, Fish
Cat

我想将它们分成不同的列进行可视化:

Dog Cat Bird Fish
1 1 1 0
1 0 1 0
1 0 0 1
0 1 0 0

如何在 Excel 或 Python 中做到这一点?谢谢!

【问题讨论】:

  • 您在预期输出中包含示例是一件好事,但我们需要看看您尝试了什么。向我们展示您的代码,以便我们提出改进建议。

标签: python excel


【解决方案1】:

假设您使用的是 pandas 和字符串答案:

>>> import pandas as pd
>>> lst = ['Dog, Cat, Bird', 'Dog, Bird', 'Dog, Fish', 'Cat']
>>> df = pd.DataFrame({'answer':lst})
>>> df
           answer
0  Dog, Cat, Bird
1       Dog, Bird
2       Dog, Fish
3             Cat

您现在可以将每个字符串拆分为一个字符串列表,并检查每个答案是否在该列表中:

>>> df.answer = df.answer.str.split(', ')  # split strings to list 
>>> for word in  ['Dog', 'Cat', 'Bird', 'Fish']:
...     df[word] = df.answer.apply(lambda x : 1 if word in x else 0)
>>> df
             answer  Dog  Cat  Bird  Fish
0  [Dog, Cat, Bird]    1    1     1     0
1       [Dog, Bird]    1    0     1     0
2       [Dog, Fish]    1    0     0     1
3             [Cat]    0    1     0     0

如果您在创建所有答案的唯一列表时遇到问题(例如,不同的答案太多),请使用集合:

>>> answer_set = set()
>>> for i in df.answer:
...     answer_set.update(set(i))
>>> answer_list = list(answer_set)
>>> answer_list
['Fish', 'Cat', 'Bird', 'Dog']

【讨论】:

    【解决方案2】:
    1. 您的专栏是 listlists,就像[['Dog', 'Cat', 'Bird'], ['Dog', 'Bird'], ['Dog', 'Fish'], ['Cat']]
    2. 您有预定义的选择数量,这也是一个列表。比如说['Dog', 'Cat', 'Bird', 'Fish']
    3. 最终可视化的每一列也是一个list,但有一个与之相关的key(动物),可以表示为dict。例如,第一列是visu['Dog'] = [1, 1, 1, 0],以此类推。
    4. 因此,您可以遍历您的选择 列表,并检查每只动物是否出现在您答案的每个列表列表。您可以想象这是必要的 2 个循环。下面的几行会给你一个很大的线索,但不是最终的答案。它使用 for 循环和内置 map 函数,该函数具有隐式循环。
    answer = [['Dog', 'Cat', 'Bird'], ['Dog', 'Bird'], ['Dog', 'Fish'], ['Cat']]
    choices = ['Dog', 'Cat', 'Bird', 'Fish']
    
    visu = {}
    for animal in choices:
        visu[animal] = list(map(lambda x: animal in x, answer))
    
    print(visu)
    
    1. 我建议你查看一些 python 教程和定义,主要是我用斜体格式化的术语。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多