red*_*bia 0 python dataframe pandas
我有一个熊猫数据框,例如
one two three four five
0 1 2 3 4 5
1 1 1 1 1 1
Run Code Online (Sandbox Code Playgroud)
我想要的是仅能够将选定数量的列转换为列表,这样我们可以获得:
[[1,2],[1,1]]
Run Code Online (Sandbox Code Playgroud)
这是行0,1,我们在其中选择第一和第二列。
同样,如果我们选择第一,第二,第四列:
[[1,2,4],[1,1,1]]
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望避免行的迭代,因为它很慢!
您可以通过以下方式仅选择这些列:
In [11]: df[['one', 'two']]
Out[11]:
one two
0 1 2
1 1 1
Run Code Online (Sandbox Code Playgroud)
并使用tolist从基础numpy数组中获取列表列表:
In [12]: df[['one', 'two']].values.tolist()
Out[12]: [[1, 2], [1, 1]]
In [13]: df[['one', 'two', 'four']].values.tolist()
Out[13]: [[1, 2, 4], [1, 1, 1]]
Run Code Online (Sandbox Code Playgroud)
注意:除非这是您的最终游戏,否则这绝对不是必须的... 在熊猫或numpy内部进行工作将更加高效。