I would like to ask an question that is an extension on this thread:
Select rows from a DataFrame based on values in a column in pandas.
The code from this thread is listed below:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['D'] == 14])
This will yield the following result:
A B C D
7 foo three 7 14
Based on the code above, how can I return a single 'value' not a row. That is, how can I return the value '7'
or value 'foo'
as opposed to the entire row?
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.
The pandas DataFrame.at attribute is used to access a single value using the row and column labels. The “at” attribute takes a row and column labels data to get an element from a specified label position of the given DataFrame object.
loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame. Here, we will use loc() function to get cell value.
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.
@JonahWilliams was close, here's a working one:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df.loc[df['D'] == 14]['A'].index.values)
>>>[7]
print(df.loc[df['D'] == 14]['A'].values)
>>>['foo']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With