从List&Pivot,Python 3.6创建数据框

时间:2019-02-01 13:38:45

标签: python python-3.x pandas pivot

我在下面的列表中,想将值“ concept”的ot数据框转换为行中的“列”和“值” XML_List:

[{'concept': 'MEASURE', 'value': '1'}, {'concept': 'INDIGENOUS_STATUS', 'value': 'IM'}, {'concept': 'ASGS_2011', 'value': '0'}, {'concept': 'FREQUENCY', 'value': 'A'}]

将列表转换为数据框:

XML_SeriesKey = pd.DataFrame(XML_List)

print(XML_SeriesKey)

         concept value
0            MEASURE     1
1  INDIGENOUS_STATUS    IM
2          ASGS_2011     0
3          FREQUENCY     A

预期:

MEASURE INDIGENOUS_STATUS   ASGS_2011   FREQUENCY
1       IM                  0           A

从列表创建数据框时我们可以做到吗?

XML_SeriesKey = pd.DataFrame(XML_List) # Any possibility while creating Dataframe?

1 个答案:

答案 0 :(得分:2)

zip使用列表理解:

v =  [(x.get('concept'), x.get('value')) for x in XML_List]
cols, vals = zip(*v)

XML_SeriesKey= pd.DataFrame([vals], columns=cols)
print(XML_SeriesKey)
  MEASURE INDIGENOUS_STATUS ASGS_2011 FREQUENCY
0       1                IM         0         A

或从concept创建索引并转置:

XML_SeriesKey = pd.DataFrame(XML_List).set_index('concept').T
XML_SeriesKey.columns.name = None

print(XML_SeriesKey)
        MEASURE INDIGENOUS_STATUS ASGS_2011 FREQUENCY
value         1                IM         0         A