【问题标题】:Dict of lists to df列表的字典到 df
【发布时间】:2016-11-17 10:24:22
【问题描述】:

我有一个这样的列表:

    {291840: ['http://www.rollanet.org', 'http://www.rollanet.org'], 
     291841: ['http://www.superpages.com', 'http://www.superpages.com], 
     291848: ['http://www.drscore.com/App/ScoreDr', 'http://www.drscore.com'],...etc }

我想将其转换为两列数据框,一列用于subj_id,另一列用于对应列表。每行将是字典的键,列是使用from_dict 将方向设置为索引的值(列表)。根据文档:“orient:如果键应该是行,则传递‘index’。”

names = ['subj_id', 'URLs']

dfDict = pd.DataFrame(columns = names)
dfDict.from_dict(listDict, orient = 'index')

相反,我得到一个数据框,其中将列表的每个元素作为一列。我只想要两列。一个用于subj_ID,另一个用于与subj_ID 关联的URL 列表。

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    我认为你需要:

    listDict = {291840: ['http://www.rollanet.org', 'http://www.rollanet.org'], 
         291841: ['http://www.superpages.com', 'http://www.superpages.com'], 
         291848: ['http://www.drscore.com/App/ScoreDr', 'http://www.drscore.com']}
    
    names = ['subj_id', 'URLs']
    
    df = pd.DataFrame(listDict).stack().reset_index(drop=True, level=0).reset_index()
    df.columns = names
    print (df)
       subj_id                                URLs
    0   291840             http://www.rollanet.org
    1   291841           http://www.superpages.com
    2   291848  http://www.drscore.com/App/ScoreDr
    3   291840             http://www.rollanet.org
    4   291841           http://www.superpages.com
    5   291848              http://www.drscore.com
    

    旧答案:

    df = pd.DataFrame.from_dict(listDict, orient='index').stack().reset_index(drop=True, level=1)
    

    如果需要在URLs 列中列出,请使用list comprehensions

    df = pd.DataFrame({'subj_id': pd.Series([k for k,v in listDict.items()]),
                       'URLs': pd.Series([v for k,v in listDict.items()])}, columns = names)
    print (df)
       subj_id                                               URLs
    0   291840  [http://www.rollanet.org, http://www.rollanet....
    1   291841  [http://www.superpages.com, http://www.superpa...
    2   291848  [http://www.drscore.com/App/ScoreDr, http://ww...
    

    【讨论】:

    • 在我的例子中,每个 URL 列表都有不同的大小。所以用你的代码我得到了错误“ValueError:数组必须都是相同的长度”
    • jezreals 以前(已删除)的答案适用于不同大小:pd.DataFrame.from_dict(listDict, orient='index').stack().reset_index(drop=True, level=1)跨度>
    • @Skirrebattie - 谢谢,我添加旧答案
    【解决方案2】:

    由于我来不及给出 jezrael 的答案,这里有一个有趣的方法:

    pd.concat([pd.Series(v, [k] * len(v)) for k, v in listDict.items()]) \
        .rename_axis('subj_id').reset_index(name='urls')
    

    【讨论】:

    • 这是一种可能的方法,但出于我的目的,我想将每个 URL 列表保存在一起以用于其各自的 subj_id
    猜你喜欢
    • 2021-04-30
    • 1970-01-01
    • 2019-12-31
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2023-02-06
    相关资源
    最近更新 更多