如何将dict转换为系列(dtype:object)

时间:2018-12-07 08:51:50

标签: python pandas

我手里有一个字典。我需要将此dict变量转换为系列,例如读取csv文件。我该怎么办?

dict = {
 'confidentiality': 'complete', 
 'integrity': 'complete', 
 'access_complexity': 'high', 
 'availability': 'complete', 
 'authentication': 'none', 
 'cpe_type': 'application'
}

我尝试:

import pandas as pd
series = pd.Series(dict)
print(series)

我的输出:

access_complexity              high
authentication                 none
confidentiality                complete
cpe_type                       application
integrity                      complete
dtype: object

我想要输出:

0    complete
Name: confidentiality, Length: 1, dtype: object

0    complete
Name: integrity, Length: 1, dtype: object

0    high
Name: access_complexity, Length: 1048, dtype: object

...

1 个答案:

答案 0 :(得分:1)

您可以将变量dict更改为d,因为使用python代码字,然后使用Series构造函数进行迭代:

d = {
 'confidentiality': 'complete', 
 'integrity': 'complete', 
 'access_complexity': 'high', 
 'availability': 'complete', 
 'authentication': 'none', 
 'cpe_type': 'application'
}

for k, v in d.items():
    print (pd.Series([v], name=k))

0    complete
Name: confidentiality, dtype: object
0    complete
Name: integrity, dtype: object
0    high
Name: access_complexity, dtype: object
0    complete
Name: availability, dtype: object
0    none
Name: authentication, dtype: object
0    application
Name: cpe_type, dtype: object