我用这段代码创建了一个字典:
dat[r["author_name"]] = (r["num_deletions"], r["num_insertions"],
r["num_lines_changed"], r["num_files_changed"], r["author_date"])
然后我想用这些字典创建一个带列的熊猫
author_name | num_deletions | num_insertions | num_lines_changed |num_files changed | author_date
我试过这个:
df = pd.DataFrame(list(dat.iteritems()),
columns=['author_name',"num_deletions", "num_insertions", "num_lines_changed",
"num_files_changed", "author_date"])
但它不起作用,因为它仅将字典的键和元组读取为两列而不是六列。那么我怎样才能将元组中的五个条目中的每一个都分成自己的列
您需要在同一嵌套级别的键和值:
df = pd.DataFrame([(key,)+val for key, val in dat.items()],
columns=["author_name", "num_deletions",
"num_insertions", "num_lines_changed",
"num_files_changed", "author_date"])
你也可以使用
df = pd.DataFrame.from_dict(dat, orient='index').reset_index()
df.columns = ["author_name", "num_deletions",
"num_insertions", "num_lines_changed",
"num_files_changed", "author_date"]
如果您有大约 10,000 行或更多行,这似乎会更快一些。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句