【问题标题】:How can I convert list to DataFrame, where items of list will act as column in DataFrame?如何将列表转换为 DataFrame,其中列表项将充当 DataFrame 中的列?
【发布时间】:2015-02-20 06:03:39
【问题描述】:

假设,我有一个如下列表:

L =[
    [11, ['Blue','Green','Yellow'] , 1],
    [21, ['White','Green','Brown'] , 0],
    [31, ['Orange','Yellow']       , 0],
    [41, ['White','Orange','Brown'], 1],
   ] ^           ^^^                 ^
     Id         Colors              vote

如何将此列表转换为颜色也是列的 DataFrame。

     Id      Blue    Green    Yellow    White    Brown    Orange    vote
0    11      1       1        1         0        0        0         1   
1    21      0       1        0         1        1        0         0
2    31      0       0        1         0        0        1         0 
3    41      0       0        0         1        1        1         1

这里,df[Id][color] 表示颜色是否存在于 Id 中。

我认为,我可以以迭代的方式做到这一点。有没有最简单的方法可以做到这一点。

【问题讨论】:

    标签: python list pandas dataframe


    【解决方案1】:

    这是一种(迭代方式),不知道如何矢量化。

    from itertools import chain
    import pandas as pd
    
    L = [
        [11, ['Blue','Green','Yellow'] , 1],
        [21, ['White','Green','Brown'] , 0],
        [31, ['Orange','Yellow']       , 0],
        [41, ['White','Orange','Brown'], 1],
    ]
    
    colors = set(chain(*(row[1] for row in L)))
    def row2obj(row):
        obj = {c: int(c in row[1]) for c in colors}
        obj['id'] = row[0]
        obj['vote'] = row[2]
        return obj
    
    df = pd.DataFrame.from_records(row2obj(row) for row in L)
    

    【讨论】:

    • 当 no_row=1600000 和 no_colors=230000 时应用你的技术是否可行?
    • 不确定,需要时间看看。然而,一个包含 230,000 列的 DataFrame 似乎并不是一个好主意。也许使用稀疏对象(DataFrame 或 scipy.sparse)。一个“信封背面”计算(假设 int 是 8 个字节)你得到(1600000* 230000*8)/1000000000 = 2944 GB。
    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 2022-01-07
    • 1970-01-01
    • 2016-12-01
    • 2021-03-01
    • 1970-01-01
    • 2013-11-04
    • 2020-09-03
    相关资源
    最近更新 更多