【问题标题】:column of lists to lists and dictionaries列表和字典的列表列
【发布时间】:2022-01-22 12:41:11
【问题描述】:

在数据框中有两列,我想使用第一列值作为键,另一列作为字典

假设df如下

Variable Value Value Distribution
1 First Color ['Black', 'Blue', 'Green', 'Red', 'Purple'] [0.3, 0.25, 0.2, 0.15, 0.1]
5 Second Color ['Deep Blue', 'Teal', 'Green', 'Purple ', 'Red... [0.5, 0.25, 0.15, 0.25, 0.25, 0.15, 0.1]
6 Third Color ['Red', 'Orange', 'Yellow', 'Green', 'Blue', '... [1.0, 0.0, 0.0, 0.0, 0.0, 0.0]

所以假设我想创建一个类似的 dic

{'第一种颜色':{'Black':0.3,'Blue':0.25,'Green':0.2,'Red':0.15,'Purple':0.1}

所以我尝试了以下

dict(zip(df['Value'],df['Value Distribution']))

将第二个和第三个列值压缩到一个字典中,而不是它创建了这个字典

"['Black', 'Blue', 'Green', 'Red', 'Purple']":"[0.3, 0.25, 0.2, 0.15, 0.1]" 将列表读取为字符串

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:
    dct = df.set_index('Variable').apply(lambda x: dict(zip(x["Value"], x["Value Distribution"])), axis=1).to_dict()
    

    输出:

    >>> dct
    {'First Color': {'Black': 0.3,
      'Blue': 0.25,
      'Green': 0.2,
      'Red': 0.15,
      'Purple': 0.1}}
    

    【讨论】:

    • 您也可以这样做:.apply(lambda x: dict(zip(x["Value"], x["Value Distribution"])), axis=1)。稍微短一点:)
    • 啊,那不是很酷,但它更短,所以我会去的。
    【解决方案2】:

    试试explodegroupby

    df = df.explode(["Value", "Value Distribution"])
    >>> df.groupby("Variable").apply(lambda x: dict(zip(x["Value"],x["Value Distribution"]))).to_dict()
    {'First Color': {'Black': 0.3,
      'Blue': 0.25,
      'Green': 0.2,
      'Red': 0.15,
      'Purple': 0.1},
     'Second Color': {'Deep Blue': 0.5,
      'Teal': 0.25,
      'Green': 0.15,
      'Purple ': 0.25,
      'Red': 0.25},
     'Third Color': {'Red': 1.0,
      'Orange': 0.0,
      'Yellow': 0.0,
      'Green': 0.0,
      'Blue': 0.0}}
    

    【讨论】:

    • 每当我尝试使用 df.explode ValueError 在 ValueError 引发时:列必须是标量
    • 我认为您需要更新版本的 pandas(1.3 或更高版本)。也许尝试更新软件包?
    【解决方案3】:

    这可能是使用iterrows 最简单的布局:

    df = pd.DataFrame(
        data = [
            ['First colour', ['Black', 'Blue', 'Green', 'Red', 'Purple'], [0.3, 0.25, 0.2, 0.15, 0.1]],
            ['Second Color', ['Red', 'Orange', 'Yellow', 'Green', 'Blue'], [0.5, 0.25, 0.15, 0.25, 0.25, 0.15, 0.1]]
        ],
        columns=['Variable', 'Value', 'Value Distribution']
    )
    
    dict_result = {}
    for index, row in df.iterrows():
        dict_result[row['Variable']] = dict(zip(row['Value'],row['Value Distribution']))
    

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 2018-02-06
      • 2020-05-11
      • 2016-01-31
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多