简体   繁体   English

如何使用字典中的键作为索引创建 pandas DataFrame? [蟒蛇,熊猫]

[英]How can I create a pandas DataFrame with keys from a dictionary as my index? [Python, pandas]

Let's say I have this dictionary:假设我有这本字典:

d = {'Name1': (33, 'String1'), 'Name2': (59, 'String2')} d = {'Name1': (33, 'String1'), 'Name2': (59, 'String2')}

And all I want to do is print a DataFrame with pandas, where the index are my keys and I'll have two columns where I'll put the values of the respective keys in it.我想要做的就是打印带有 pandas 的 DataFrame,其中索引是我的键,我将有两列,我将在其中放入相应键的值。

Thanks a lot in advance!提前非常感谢!

if you want the keys of the dictionary to be the index then you can do this:如果您希望字典的键成为索引,那么您可以这样做:

d = {'Name1': (33, 'String1'), 'Name2': (59, 'String2')}
df=pd.DataFrame(d.values(),index=d.keys())
print(df)

output: output:

        0        1
Name1  33  String1
Name2  59  String2

pd.DataFrame.from_dict(d, orient='index', columns=['column A', 'column B'])

Have you tried to do this.你有没有试过这样做。 Just create the dataframe using d and then transpose the dataframe.只需使用d创建 dataframe,然后转置 dataframe。

import pandas as pd
d = {'Name1': (33, 'String1'), 'Name2': (59, 'String2')}
df=pd.DataFrame(d).T
df = df.rename(columns={0:'column1',1:'column2'})
print (df)

If you want a single line, then it is:如果你想要一行,那么它是:

df=pd.DataFrame(d).T.rename(columns={0:'column1',1:'column2'})

The output will be as follows: output 如下:

      column1  column2
Name1      33  String1
Name2      59  String2

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

相关问题 如何从python字典创建pandas dataframe? - How to create pandas dataframe from python dictionary? 如何为 python pandas 数据框创建索引? - How can I create index for python pandas dataframe? 从熊猫数据框中按索引创建字典 - Create dictionary by index in from pandas dataframe 熊猫:如何从字典创建日期时间数据帧索引 - Pandas: How to create a datetime dataframe index from dictionary Pandas 将 dataframe 转换为具有唯一键的字典作为(索引,列)来自 dataframe - Pandas convert dataframe to dictionary with unique keys as (index,col) from the dataframe 如何将带有元组键的 python 字典转换为 Pandas 多索引数据框? - How can i convert a python dictionary with tuple keys to a pandas multi Index data frame? 如何为列表中的一个键创建具有多个值的 Python 字典,然后创建具有一列和多行的 pandas 数据框 - How can I create a Python dictionary with multiple values for one key from a list, to then create a pandas dataframe with one column and multiple rows 如何从我的老字典创建熊猫数据框? - How to create pandas dataframe from my oredered dictionary? 如何使用python的pandas从数据框创建字典词典 - How to create dictionary of dictionaries from a dataframe using python's pandas 如何从具有特定格式的 Pandas 数据框创建字典 - How do I create a dictionary from a Pandas dataframe with a specific format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM