Python 如何将 Pandas DataFrame 的列转换为列表列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15112234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert columns of a pandas DataFrame into a list of lists?
提问by naz
I have a pandas DataFrame with multiple columns.
我有一个包含多列的 Pandas DataFrame。
2u 2s 4r 4n 4m 7h 7v
0 1 1 0 0 0 1
0 1 0 1 0 0 1
1 0 0 1 0 1 0
1 0 0 0 1 1 0
1 0 1 0 0 1 0
0 1 1 0 0 0 1
What I want to do is to convert this pandas.DataFrameinto a list like following
我想要做的是将其转换pandas.DataFrame为如下列表
X = [
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 1]
]
2u 2s 4r 4n 4m 7h 7v are column headings. It will change in different situations, so don't bother about it.
2u 2s 4r 4n 4m 7h 7v 是列标题。它会在不同的情况下发生变化,所以不要理会它。
采纳答案by eumiro
It looks like a transposed matrix:
它看起来像一个转置矩阵:
df.values.T.tolist()
[list(l) for l in zip(*df.values)]
[[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 1]]
回答by Ravi Teja Mureboina
To change Dataframe into list use tolist() function to convert Let use say i have Dataframe df
要将 Dataframe 更改为列表,请使用 tolist() 函数进行转换假设我有 Dataframe df
to change into list you can simply use tolist() function
要更改为列表,您只需使用 tolist() 函数
df.values.tolist()
You can also change a particular column in to list by using
您还可以使用以下方法将特定列更改为列表
df['column name'].values.tolist()

