Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting single values from pandas dataframe using lists

import numpy as np
import pandas as pd

ind = [0, 1, 2]
cols = ['A','B','C']
df = pd.DataFrame(np.arange(9).reshape((3,3)),columns=cols)

Say you have a pandas dataframe df looking like:

    A  B  C
 0  0  1  2
 1  3  4  5
 2  6  7  8    

If you want to capture a single element from each column in cols at a specific index ind the output should look like a series:

 A  0
 B  4
 C  8

What I've tried so far was:

 df.loc[ind,cols]

which gives the undesired output:

   A  B  C
0  0  1  2
1  3  4  5
2  6  7  8

Any suggestions?

context: The next step would be mapping the output of an df.idxmax() call of one dataframe onto another dataframe with the same column names and indexes, but I can likely figure that out if I know how to do the above mentioned transformation .

like image 379
edager Avatar asked Oct 18 '17 17:10

edager


People also ask

How do I select a specific value in pandas?

Select Data Using Location Index (. This means that you can use dataframe. iloc[0:1, 0:1] to select the cell value at the intersection of the first row and first column of the dataframe. You can expand the range for either the row index or column index to select more data.

How do you select a single value from a DataFrame in Python?

You can access a single value from a DataFrame in two ways. Method 1: DataFrame.at[index, column_name] property returns a single value present in the row represented by the index and in the column represented by the column name. Method 2: Or you can use DataFrame.

How do you extract a single element from a DataFrame?

get_value() function is used to quickly retrieve the single value in the data frame at the passed column and index. The input to the function is the row label and the column label.

How filter DataFrame with list of values?

isin() to Select Rows From List of Values. DataFrame. isin() method is used to filter/select rows from a list of values. You can have the list of values in variable and use it on isin() or use it directly.


1 Answers

you can use DataFrame.lookup():

In [6]: pd.Series(df.lookup(df.index, df.columns), index=df.columns)
Out[6]:
A    0
B    4
C    8
dtype: int32

or:

In [14]: pd.Series(df.lookup(ind, cols), index=df.columns)
Out[14]:
A    0
B    4
C    8
dtype: int32

Explanation:

In [12]: df.lookup(df.index, df.columns)
Out[12]: array([0, 4, 8])
like image 104
MaxU - stop WAR against UA Avatar answered Sep 21 '22 00:09

MaxU - stop WAR against UA