【问题标题】:Using multiple lists how do we assign which list our row came from to a new column使用多个列表我们如何将我们的行来自哪个列表分配给新列
【发布时间】:2021-12-19 21:33:37
【问题描述】:

我有几个英文单词列表。如何在 DataFrame 中创建一列,告诉我每个单词来自哪个列表。因此,将来随着从新列表中添加更多单词,我可以跟踪单词来自哪个列表?

list_1 = [['ant', 3] ['bat', 3] ['cat', 3]]

df = pd.DataFrame(list_1, columns = ['word', 'length'], dtype = str)

如何将 list_2 数据添加到此数据框并确定数据来自 source 列下的哪些列表?

list_2 = [['rose', 4] ['tulip', 5] ['lilac', 5] ['daisy', 5]]

预期输出:

   source   word  length
0  list_1    ant       3
1  list_1    bat       3
2  list_1    cat       3
3  list_2   rose       4
4  list_2  tulip       5
5  list_2  lilac       5
6  list_2  daisy       5

【问题讨论】:

  • 认真的吗?数据图像已经很痛苦了,但是手写数据图像真的更糟糕...请提供文本
  • 看看这是否更清楚@mozway
  • 我提供了答案,请编辑您的问题以删除您的图片并用漂亮的基于文本的表格替换它
  • 我已经查看了编辑的格式并将应用于未来的问题@mozway

标签: pandas list row multiple-columns


【解决方案1】:

我会这样做,使用字典来保存列表,并使用数据框构造函数进行小理解:

import pandas as pd

list_1 = ['ant', 'bat', 'cat']
list_2 = ['rose', 'tulip', 'lilac', 'daisy']

lists = {'list_1': list_1, 'list_2': list_2}


df = pd.DataFrame([(k,e,len(e)) for k,l in lists.items() for e in l],
                  columns=['source', 'word', 'length'])

输出:

   source   word  length
0  list_1    ant       3
1  list_1    bat       3
2  list_1    cat       3
3  list_2   rose       4
4  list_2  tulip       5
5  list_2  lilac       5
6  list_2  daisy       5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多