【问题标题】:Python dictionary conversionPython字典转换
【发布时间】:2020-01-24 05:40:40
【问题描述】:

我有一本 Python 字典:

adict = {
    'col1': [
        {'id': 1, 'tag': '#one#two'},
        {'id': 2, 'tag': '#two#'},
        {'id': 1, 'tag': '#one#three#'}
    ]
}

我想要的结果如下:

Id tag
1  one,two,three
2  two

有人能告诉我怎么做吗?

【问题讨论】:

  • 使用for-loop 处理字典并将其转换为列表列表或新字典。
  • 结果中的标签需要特殊顺序吗?

标签: python dictionary nested


【解决方案1】:

试试这个

import pandas as pd
d={'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}

df = pd.DataFrame()
for i in d:
    for k in d[i]:
        t = pd.DataFrame.from_dict(k, orient='index').T
        t["tag"] = t["tag"].str.replace("#",",")
        df = pd.concat([df,t])

tf = df.groupby(["id"])["tag"].apply(lambda x : ",".join(set(''.join(list(x)).strip(",").split(","))))

【讨论】:

  • 它看起来像一个低效的解决方案,通过嵌套的dicts迭代会得到O(n^2)
  • 我没有使用 for 循环,而是使用了您的 groupby 查询并得到了结果 df = pd.DataFrame(d) df[["col1","col2"]] = pd.DataFrame(df. col1.values.tolist(),index=df.index) df['col1'] = df.col1.str.replace('#',',') df = df.groupby(["col2"])[ "col1"].apply(lambda x : ",".join(set(''.join(list(x)).strip(",").split(","))))
【解决方案2】:

这是一个简单的代码

import pandas as pd

d = {'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}


df = pd.DataFrame(d)

df['Id'] = df.col1.apply(lambda x: x['id'])

df['tag'] = df.col1.apply(lambda x: ''.join(list(','.join(x['tag'].split('#')))[1:]))

df.drop(columns = 'col1', inplace = True)
Output:
Id Tag
1  one, two
2  two
1  one, three 

【讨论】:

  • 这与 OP 所期望的输出不同。
【解决方案3】:

如果标签的顺序很重要,首先删除尾随# 并按# 拆分,然后按组删除重复项和join

df = pd.DataFrame(d['col1'])
df['tag'] = df['tag'].str.strip('#').str.split('#')
f = lambda x: ','.join(dict.fromkeys([z for y in x for z in y]).keys())
df = df.groupby('id')['tag'].apply(f).reset_index()
print (df)
   id            tag
0   1  one,two,three
1   2            two

如果标签的顺序对于删除重复项不重要,请使用sets:

df = pd.DataFrame(d['col1'])
df['tag'] = df['tag'].str.strip('#').str.split('#')
f = lambda x: ','.join(set([z for y in x for z in y]))
df = df.groupby('id')['tag'].apply(f).reset_index()
print (df)
   id            tag
0   1  three,one,two
1   2            two

【讨论】:

    【解决方案4】:

    我尝试如下

    import pandas as pd
    a = {'col1':[{'id':1, 'tag':'#one#two'},{'id':2, 'tag':'#two#'},{'id':1, 'tag':'#one#three#'}]}
    
    df = pd.DataFrame(a)
    df[["col1", "col2"]] = pd.DataFrame(df.col1.values.tolist(), index = df.index)
    df['col1'] = df.col1.str.replace('#', ',')
    df = df.groupby(["col2"])["col1"].apply(lambda x : ",".join(set(''.join(list(x)).strip(",").split(","))))
    
    O/P:
    col2
    1    one,two,three
    2    two
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请“编辑”以添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer
    【解决方案5】:
    dic=[{'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}]
    
    row=[]
    for key in dic:
        data=key['col1']
        for rows in data:
            row.append(rows)
    df=pd.DataFrame(row)
    print(df)
    

    o

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。我建议您查看 SO 的 official How to Answer article 以及来自 Jon Skeet 的综合 blog post
    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2021-09-24
    相关资源
    最近更新 更多