[英]How to convert dictionary key as row and values as columns
How to convert nested dictionary in to data frame 如何将嵌套字典转换为数据框
My dict is below 我的字典在下面
out = {'1.2.2.2': {'DELETE': 1,
'GET': 5,
'POST': 1,
'PUT': 3},
'2.2.2.2': {'DELETE': 1,
'GET': 6,
'POST': 3,
'PUT': 3},
'3.3.3.3': {'DELETE': 0,
'GET': 6,
'POST': 2,
'PUT': 1}
I want to convert in to dataframe with column values IP, DELETE, DELETE, POST, PUT 我想转换为具有IP,DELETE,DELETE,POST,PUT列值的数据框
IP key is not in my out IP密钥不在我的外面
import dataframe
pd.DataFrame([out])
df.columns =['IP', 'DELETE', 'POST', 'PUT']
You can do it like this: 您可以这样做:
df = pd.DataFrame(columns=['DELETE', 'POST', 'PUT'])
for item in out:
list_dict = []
list_dict.append({'DELETE':out[item]['DELETE'], 'POST':out[item]['POST'], 'PUT':out[item]['PUT']})
df= df.append(list_dict)
and add a column named ID later. 稍后添加一个名为ID的列。 Like this:
像这样:
df['ID']=[0]*len(df)
Here I made all the ids 0. You can change it according to your data. 在这里,我将所有ID设为0。您可以根据自己的数据进行更改。
out = {'1.2.2.2': {'DELETE': 1,
'GET': 5,
'POST': 1,
'PUT': 3},
'2.2.2.2': {'DELETE': 1,
'GET': 6,
'POST': 3,
'PUT': 3},
'3.3.3.3': {'DELETE': 0,
'GET': 6,
'POST': 2,
'PUT': 1}}
Create the list of columns that you want included 创建要包含的列的列表
cols = ['IP', 'DELETE', 'POST', 'PUT']
The following will transpose the dataframe, reset the index, and rename the previous index as 'IP' 以下将转置数据帧,重置索引,并将先前的索引重命名为“ IP”
pd.DataFrame(out).T.reset_index().rename(columns={'index':'IP'})[cols]
the output of this will be: 其输出将是:
IP DELETE POST PUT
0 1.2.2.2 1 1 3
1 2.2.2.2 1 3 3
2 3.3.3.3 0 2 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.