Paulo
Paulo

Reputation: 11

How do I get a dataframe row to a list the index number?

I have a problem here let's say that I have this dataframe:

import pandas as pd
df = pd.DataFrame([[1, 2, 1], [1, 3, 2], [4, 6, 3], [4, 3, 4], [5, 4, 5]], columns=['A', 'B', 'C'])

>> df
   A  B  C
0  1  2  1
1  1  3  2
2  4  6  3
3  4  3  4
4  5  4  5

Let's say that I have to get the row where A = 4:

2 4 6 3 and 3 4 3 4

How can I convert these data to a list WITH THE INDEX number?

Paulo

Upvotes: 1

Views: 44

Answers (2)

boot-scootin
boot-scootin

Reputation: 12515

You only want all that data to be in a list? How about something like this:

>>> df.reset_index(drop=False).query('A == 4').values.tolist()
[[2, 4, 6, 3], [3, 4, 3, 4]]

Where the index is the 0th item in each sublist, and the values for each column are the remaining items in each sublist (i.e. from indexes 1 to 3)

Resetting the index using reset_index(drop=False) simply adds an index column to the DataFrame, consisting of whatever you index was previously, and makes it easy to get all these data into your list-sublist format.

Upvotes: 1

Abbas
Abbas

Reputation: 643

Use filtering

This should work

df[df.A == 4]

Upvotes: 0

Related Questions