从字典元素创建Pandas数据框

Luk*_*asz 5 python dictionary pandas

我正在尝试从字典中创建一个pandas数据帧.字典设置为

nvalues = {"y1": [1, 2, 3, 4], "y2": [5, 6, 7, 8], "y3": [a, b, c, d]}
Run Code Online (Sandbox Code Playgroud)

我希望数据帧只包括"y1"和" y2".到目前为止,我可以使用

df = pd.DataFrame.from_dict(nvalues)
df.drop("y3", axis=1, inplace=True)
Run Code Online (Sandbox Code Playgroud)

我想知道是否有可能在没有的情况下实现这一目标 df.drop()

Joh*_*nck 4

您可以columnsDataFrame构造函数中指定:

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

   y1  y2
0   1   5
1   2   6
2   3   7
3   4   8
Run Code Online (Sandbox Code Playgroud)