How can I convert columns of a pandas DataFrame into a list of lists?
Question:
I have a pandas DataFrame with multiple columns.
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.DataFrame
into a list like following
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.
Answers:
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]]
To change Dataframe into list use tolist() function to convert
Let use say i have Dataframe df
to change into list you can simply use tolist() function
df.values.tolist()
You can also change a particular column in to list by using
df['column name'].values.tolist()
I have a pandas DataFrame with multiple columns.
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.DataFrame
into a list like following
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.
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]]
To change Dataframe into list use tolist() function to convert
Let use say i have Dataframe df
to change into list you can simply use tolist() function
df.values.tolist()
You can also change a particular column in to list by using
df['column name'].values.tolist()