【问题标题】:How to access the items in list from Dataframe against each index item? [duplicate]如何针对每个索引项从 Dataframe 访问列表中的项目? [复制]
【发布时间】:2020-04-25 15:24:05
【问题描述】:

考虑下面的表格(数据框)。

需要列表中的每个项目与其索引相对应,如下所示。在 python 中执行此操作的可能方法是什么?

如果问题符合上下文,任何人都可以调整它。

【问题讨论】:

标签: python-3.x list dictionary


【解决方案1】:

您可以使用pandas 库和explode 方法来执行此操作。这是您的代码的外观 -

import pandas as pd

df = [["A", [1,2,3,4]],["B",[9,6,4]]]

df =  pd.DataFrame(df, columns = ['Index', 'Lists'])

print(df)

df = df.explode('Lists').reset_index(drop=True)

print(df)

您的输出将是 -

  Index         Lists
0     A  [1, 2, 3, 4]
1     B     [9, 6, 4]


  Index Lists
0     A     1
1     A     2
2     A     3
3     A     4
4     B     9
5     B     6
6     B     4

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    相关资源
    最近更新 更多