python - `[row_index, [elements]]` 的嵌套列表到 Pandas 数据框?

标签 python python-3.x pandas dataframe nested

我有一个列表:

list1= [[1, ['dog', 'slow']], 
        [1, [5, 4]], 
        [1, ['mice', 'cat']], 
        [2, ['cat', 'fast']], 
        [2, [6, 6]], 
        [2, ['cat', 'mice']],
        [3, ['tree', 'hurry']], 
        [3, [7, 5]], 
        [3, ['mice', 'cat']]]

我想从这个嵌套列表中形成一个数据框。我期望这样的输出:

col0       col1            col2         col3
 1    ['dog', 'slow']     [5, 4]   ['mice', 'cat']
 2    ['cat', 'fast']     [6, 6]   ['cat', 'fast']
 3    ['tree', 'hurry']   [7, 5]   ['mice', 'cat']

最佳答案

从原始数据创建一个中间数据框:

first_df = pd.DataFrame(list1)

通过将第二列 reshape 为三列二维数组,将其用作最终数据帧的数据。使用第一列的唯一值作为索引:

pd.DataFrame(first_df[1].values.reshape(3, -1), index=first_df[0].unique())
#               0       1            2
#1    [dog, slow]  [5, 4]  [mice, cat]
#2    [cat, fast]  [6, 6]  [cat, mice]
#3  [tree, hurry]  [7, 5]  [mice, cat]

关于python - `[row_index, [elements]]` 的嵌套列表到 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52340045/

相关文章:

python-3.x - 如何在 2 小时后运行 AWS Lambda

pandas - 使用 Pandas 将 csv 转换为 Parquet 文件时出错

python - 如何替换 Pandas 中的异常值数据?

python - Numpy:在不使用 nan_to_num 的情况下乘以 NaN 值

python - FNV1A_64 不匹配

python - 获取 Jupyter Notebook 中定义的对象的源

python - Pandas 过滤和组合

python - 如何在plotly中绘制venn3

python - 如何使用python定位和读取Data Matrix代码

python - f.readline() 不捕获文件的最后一行