[英]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.