Creating a Pandas dataframe from elements of a dictionary

爷,独闯天下 提交于 2021-02-07 14:48:03

问题


I'm trying to create a pandas dataframe from a dictionary. The dictionary is set up as

nvalues = {"y1": [1, 2, 3, 4], "y2": [5, 6, 7, 8], "y3": [a, b, c, d]}

I would like the dataframe to include only "y1" and "y2". So far I can accomplish this using

df = pd.DataFrame.from_dict(nvalues)
df.drop("y3", axis=1, inplace=True)

I would like to know if it is possible to accomplish this without having df.drop()


回答1:


You can specify columns in the DataFrame constructor:

pd.DataFrame(nvalues, columns=('y1', 'y2'))

   y1  y2
0   1   5
1   2   6
2   3   7
3   4   8



回答2:


You could use a dictionary comprehension to filter out unwanted keys like so:

df = pd.DataFrame.from_dict({k: v for k, v in nvalues.items() if k != 'y3'})

to get:

   y1  y2
0   1   5
1   2   6
2   3   7
3   4   8

There are of course quite a few ways to remove one or more keys from a dictionary.



来源:https://stackoverflow.com/questions/37934969/creating-a-pandas-dataframe-from-elements-of-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!