How to extract a cell value from a Dataframe in Pandas
You can use boolean indexing
with DataFrame.loc
for filter by condition and by column name:
s = df.loc[df['instrument_token'].eq(12295682), 'tradingsymbol']
#alternative
s = df.loc[df['instrument_token'] == 12295682, 'tradingsymbol']
And then get first value of Series
:
a = s.iat[0]
a = s.iloc[0]
a = s.tolist()[0]
a = s.to_array()[0]
#general solution if not match condition and select first value failed
a = next(iter(s), 'no match')
Another idea is use DataFrame.set_index
fo index by column instrument_token
:
df = df.set_index('instrument_token')
Anf then select by DataFrame.loc
or DataFrame.at
:
a = df.loc[12295682, 'tradingsymbol']
a = df.at[12295682, 'tradingsymbol']
How to get a value from a cell of a dataframe by position or label?
First thing's first. ix
is deprecated, but ix
allowed you to mix labels and indexers, and made a lot of guesses about what it was passed.
In today's day and age (with the current stable release being v0.22
), ix
is deprecated, so stick to explicit label or positional based indexers: loc
for label based slicing, iloc
for index based slicing; at
for label based item access, and iat
for index based item access.
If you know what your labels are, use at
to access a single item -
df.at['Header I, II and III; x', df.columns[-1]]
If you know the position, use iat
-
df.iat[2, -1]
In general, use *at
when you want to access a single element, and *loc
when you want to access a row/column slice.
How to get the content of a cell in a pandas dataframe
What about :
print(data["Monkey"]["Name"].values[0])
As previously, you extract the row/column you want, based on the row's index and column name. Then .values
turn the result dataframe into a numpy arrays of values. Finally, just retrieve the first (and only) element
You might also be able to use :
print(data["Monkey"].iloc[0]["Name"])
Get t-1 value (from previous cell) in a pandas dataframe
Use shift on the columns to compute:
cols = ["Austria", "Belgium", "France"]
df[cols] = df[cols].shift()
print(df)
Output
Timestamp Austria Belgium France
1 1993-11-01 NaN NaN NaN
2 1993-11-02 6.11 7.01 7.69
3 1993-11-03 6.18 7.05 7.61
4 1993-11-04 6.17 7.20 7.67
5 1993-11-15 6.17 7.50 7.91
As an alternative:
df.iloc[:, 1:] = df.iloc[:, 1:].shift()
print(df)
Dealing with multiple values in Pandas Dataframe Cell
Use:
#unpivot by melt
df = df.melt('solution_id')
#create lists by split #
df['value'] = df['value'].str.split('#')
#repeat rows by value column
df = df.explode('value')
#counter for new columns names
df['g'] = df.groupby(['solution_id','variable']).cumcount().add(1)
#pivoting and sorting MultiIndex
df = (df.pivot('solution_id',['variable', 'g'], 'value')
.sort_index(level=1, axis=1, sort_remaining=False))
#flatten MultiIndex
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
print (df)
type_labour_1 labour_unit_1 est_labour_quantity_1 \
solution_id
10 WorkA Person 2.0
11 WorkC Person 3.0
est_labour_costs_1 est_labour_total_costs_1 type_labour_2 \
solution_id
10 300.0 600.0 WorkB
11 300.0 900.0 WorkD
labour_unit_2 est_labour_quantity_2 est_labour_costs_2 \
solution_id
10 Person 2.0 300.0.
11 Person 2.0 300.0.
est_labour_total_costs_2
solution_id
10 600.0
11 600.0
extracting dataframe cell value in for loop
If you want to iterate through each i,j value of the data frame, you can do something like this:
for i in range(df.shape[0]):
for j in range(df.shape[1]):
print(df.iloc[i, j])
Get a numerical cell value in a Pandas DataFrame
It would be this simple:
float(df['column_name'][row_number])
where:
df
is the dataframecolumn_name
is the name of the columnrow_number
is an integer number for the row.
the function float()
does the conversion to a float.
Example dataframe:
year average_temperature
0 1820 -6.1100
1 1821 -5.5600
2 1822 -5.8500
3 1823 -6.3550
4 1824 -5.1754
5 1825 -5.1500
The float of the row 3 average temperature:
float(df['average_temperature'][3])
Related Topics
Sklearn Error Valueerror: Input Contains Nan, Infinity or a Value Too Large for Dtype('Float64')
Get the Last Sunday and Saturday'S Date in Python
Finding the Two Closest Numbers in a List Using Sorting
How to Set the Default Python Path for Anaconda on Linux
Python Opencv - Add Alpha Channel to Rgb Image
Pandas Concat: Valueerror: Shape of Passed Values Is Blah, Indices Imply Blah2
Test If Dictionary Key Exists, Is Not None and Isn't Blank
How to Pass a Dictionary Object as Parameter for a Function in Python
Python - Converting a List of 2 Digit String Numbers to a List of 2 Digit Integers
Beautifulsoup: Get the Contents of a Specific Table
How to Create a Common Function to Execute a Python Script in Jenkins
Pandas: Merging Two Columns into One With Corresponding Values
How to Loop Over Grouped Pandas Dataframe
Recursive Function to Go Inside Dictionary of Dictionary
Large File Crashing on Jupyter Notebook