How can you convert a single df column to a list of lists? using the df below, how can you return X
to a list of lists.
df = pd.DataFrame({
'X' : [1,2,3,4,5,2,3,4,5,6],
'Y' : [11,12,13,14,15,11,12,13,14,15],
})
l = df['X'].values.tolist()
[1, 2, 3, 4, 5, 2, 3, 4, 5, 6]
Converting two columns is possible:
l = df.values.tolist()
[[1, 11], [2, 12], [3, 13], [4, 14], [5, 15], [2, 11], [3, 12], [4, 13], [5, 14], [6, 15]]
But I just want X.
[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
Some of these solutions seem overcomplicated. I believe this should do the job.
res_list = [[elem] for elem in df['X']]
If you want this output
[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
when starting with the input: [1,2,3,4,5,2,3,4,5,6]
then this should work fine
l = [[i] for i in df['X'].values.tolist()]
Try this:
df['X'].apply(lambda x: [x]).tolist()
output:
[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
IIUC
df.X.values[:,None].tolist()
Out[85]: [[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.