[英]How to create a dataframe from a python dictionary of lists?
import pandas as pd
new_dict = {'mid': ['1', '2'], 'type': ['a', 'b']}
df = pd.DataFrame(new_dict.items(), columns=list(new_dict), index=None)
print(df)
This print out as:这打印为:
mid type
0 mid [1, 2]
1 type [a, b]
But I hope it prints out as:但我希望它打印为:
mid type
1 a
2 b
Is that possible?那可能吗?
--Edit : As @DeepSpace pointed out in the comments to my answer, your mistake was in passing the new_dict.items() function result as the data rather than just the dict itself. --编辑:正如@DeepSpace 在对我的回答的评论中指出的那样,您的错误在于将 new_dict.items() 函数结果作为数据传递,而不仅仅是 dict 本身。
Keeping it simple, if you just do this, without needing to specify the columns and index arguments, it works:保持简单,如果你只是这样做,而不需要指定列和索引参数,它可以工作:
new_dict = {"mid":["1","2"], "type":["a", "b"]}
df = pd.DataFrame(new_dict)
print(df)
This is the result, which I think is what you want:这就是结果,我认为这就是你想要的:
mid type
0 1 a
1 2 b
And here it is with specifying something for columns and index: new_dict = {"mid":["1","2"], "type":["a", "b"]} df = pd.DataFrame(new_dict, columns=list(new_dict), index=None) print(df)这里是为列和索引指定一些东西: new_dict = {"mid":["1","2"], "type":["a", "b"]} df = pd.DataFrame(new_dict ,列=列表(new_dict),索引=无)打印(df)
output:输出:
mid type
0 1 a
1 2 b
And, if you were trying to print the Dataframe without showing the index, which seems to be your desired output, you can do this:而且,如果您尝试在不显示索引的情况下打印 Dataframe,这似乎是您想要的输出,您可以这样做:
print(df.to_string(index=False))
mid type
1 a
2 b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.