简体   繁体   English

更改 Python Pandas 中字典的结构

[英]Change structure of dictionary in Python Pandas

Is there a way of changing structure of nested dictionary?有没有办法改变嵌套字典的结构? I have a column in dataframe with many rows of dictionaries, which looks like that:我在数据框中有一列包含多行字典,如下所示:

[{'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}, {'a': 'b1', 'c': {'c1': 'x1', 'c2': 'x2'}}, {'a': 'b2', 'c': {'c1': 'n1', 'c2': 'n2'}}]

Is there a way of modifying structure, so that it will looks like有没有办法修改结构,使它看起来像

[{'b': {'c1': 'v1', 'c2': 'v2'}}, {'b1': {'c1': 'x1', 'c2': 'x2'}}, {'b2': {'c1': 'n1', 'c2': 'n2'}}]

without changing actual values?不改变实际值?

You should read about the function apply() in pandas.您应该阅读 pandas 中的函数apply()

You build a function that essentially does your dictionary manipulation :您构建了一个基本上执行字典操作的函数:

def transformation(row):
    # Where 'correspondingColumn' is the name of your initial column
    return {row[correspondingColumn]['a']: row[correspondingColumn]['c']}

Then you can use apply() to call this over all the rows of your DataFrame :然后,您可以使用apply()在 DataFrame 的所有行上调用它:

# Where 'newCol' is the name of your new column, or if you want to replace the other one, it can be the same
my_df['newCol'] = my_df.apply(transformation, axis = 1)

Complete example :完整的例子:

df = pd.DataFrame({
    'col':[{'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}]
})

def transformation(row):
    return {row['col']['a']: row['col']['c']}

df['newCol'] = df.apply(transformation, axis = 1)

# Output
                                         col                           newCol
0  {'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}  {'b': {'c1': 'v1', 'c2': 'v2'}}

Update for list of dictionaries :更新字典列表:

def transformation(row):
    return [{elem['a']: elem['c']} for elem in row['col']]

Code:代码:

d = {'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}
dic={}
dic['b'] = d['c']
dic

Output:输出:

{'b': {'c1': 'v1', 'c2': 'v2'}}

你可以做这样的事情

dict([d.values()])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM