pandas中怎么通过字典生成dataframe,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
1、将一个字典输入:
该字典必须满足:value是一个list类型的元素,且每一个key对应的value长度都相同:
(以该字典的key为columns)
>>> import pandas as pd >>> a = [1,2,3,4,5] >>> b = ["a","b","c"] >>> c = 1 >>> df = pd.DataFrame({"A":a,"B":b,"C":c}) Traceback (most recent call last): ValueError: arrays must all be same length >>> df = pd.DataFrame([a,b]) # 作为list输入,list的元素必须也是list,加入c就错误 >>> df 0 1 2 3 4 0 1 2 3 4.0 5.0 1 a b c NaN NaN # 统一一下字典每个元素值的长度 >>> b = ["a","b","c","d","e"] >>> c = ("232","sdf","345","asd",1) >>> df = pd.DataFrame({"A":a,"B":b,"C":c}) >>> df A B C 0 1 a 232 1 2 b sdf 2 3 c 345 3 4 d asd 4 5 e 1
2、将多个key相同的字典列输入:
输入为一个list,该list各个元素为dict,且key可以不同(以含最多的key的字典的key为columns):
>>> d1 = {"A":1,"B":2,"C":3} >>> d2 = {"A":"a","B":"b",} >>> d3 = {"A":(1,2),"B":"ab","C":3} >>> li = [d1,d2,d3] >>> df = pd.DataFrame(li) >>> df A B C 0 1 2 3.0 1 a b NaN 2 (1, 2) ab 3.0
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。