Niels de Vries
Niels de Vries

Reputation: 99

Extract column values from a list in a list

I have the following list in a list structure 1

How can i extract the data from all the rows in the first column (48.0, 48.01, 48.02, ...)

I expected: results[0:4][0] would extract the first 3 rows from the first column but it doesn't work, can someone explain why?

Thanks in advance!

Upvotes: 0

Views: 1179

Answers (2)

Jan
Jan

Reputation: 43169

You could simply use

result = [lst[0] for lst in results]

Upvotes: 0

azro
azro

Reputation: 54148

  • If your data is a list containing lists, use a list-comprehension

    first_col = [sublist[0] for sublist in values]
    
  • If your data is a numpy array, you can use its multi-level slicing

    first_col = values[:, 0]
    

values = [list(range(10)), list(range(10)), list(range(10)), list(range(10)), ]

first_col = [sublist[0] for sublist in values]
print(first_col)  # [0, 0, 0, 0]

import numpy as np
values = np.array(values)
first_col = values[:, 0]
print(first_col)  # [0 0 0 0]

Upvotes: 1

Related Questions