简体   繁体   English

从列表字典制作熊猫数据框

[英]Make a pandas dataframe from a dictionary of lists

My question is a bit linked to this one , except that I want to turn my lists into rows not columns, and specify the names of the columns.我的问题与这个问题有点相关,只是我想将我的列表变成行而不是列,并指定列的名称。

For example, I start with a dictionary:例如,我从字典开始:

my_dict = {'label1' : [0.1, 1.1, 32.1] , 'label2' : [12.3, 5.3, 2.4], 'label3' : [1.5, 7.5, 7.4]}

I want to be able to specify column names like:我希望能够指定列名称,例如:

cols = ['labels','val1' ,'val2, 'val3']

and create the dataframe并创建数据框

labels  | val1  | val2  | val3
label1    0.1     1.1     32.1
label2    12.3    5.3     2.4
label3    1.5     7.5     7.4

You want a transposed dataframe and then assign column names,你想要一个转置的数据框,然后分配列名,

df = pd.DataFrame(my_dict)
df = df.T.reset_index()
df.columns = cols

    labels  val1    val2    val3
0   label1  0.1     1.1     32.1
1   label2  12.3    5.3     2.4
2   label3  1.5     7.5     7.4

You can use pandas.DataFrame.from_dict but using 'orientation' of index rather than columns.您可以使用pandas.DataFrame.from_dict但使用索引的“方向”而不是列。

This allows the labels to be used as the index.这允许将标签用作索引。

df = pd.DataFrame.from_dict(my_dict, orient='index', columns =  ['val1' ,'val2', 'val3'])
df.index.name = 'labels'  # rename index column

print(df)

Output输出

      val1  val2  val3
labels                  
label1   0.1   1.1  32.1
label2  12.3   5.3   2.4
label3   1.5   7.5   7.4

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

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