有沒有辦法改變嵌套字典的結構?我在資料框中有一列包含多行字典,如下所示:
[{'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}, {'a': 'b1', 'c': {'c1': 'x1', 'c2': 'x2'}}, {'a': 'b2', 'c': {'c1': 'n1', 'c2': 'n2'}}]
有沒有辦法修改結構,使它看起來像
[{'b': {'c1': 'v1', 'c2': 'v2'}}, {'b1': {'c1': 'x1', 'c2': 'x2'}}, {'b2': {'c1': 'n1', 'c2': 'n2'}}]
不改變實際值?
uj5u.com熱心網友回復:
你應該閱讀apply()pandas 中的函式。
您構建了一個基本上執行字典操作的函式:
def transformation(row):
# Where 'correspondingColumn' is the name of your initial column
return {row[correspondingColumn]['a']: row[correspondingColumn]['c']}
然后,您可以使用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)
完整的例子:
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'}}
更新字典串列:
def transformation(row):
return [{elem['a']: elem['c']} for elem in row['col']]
uj5u.com熱心網友回復:
代碼:
d = {'a': 'b', 'c': {'c1': 'v1', 'c2': 'v2'}}
dic={}
dic['b'] = d['c']
dic
輸出:
{'b': {'c1': 'v1', 'c2': 'v2'}}
uj5u.com熱心網友回復:
你可以做這樣的事情
dict([d.values()])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484624.html
上一篇:如何讓Alexa閱讀簡單的字典?
