search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
chevron_leftRow and Column Operations Cookbook
Adding a column that contains the difference in consecutive rowsAdding a constant number to DataFrame columnsAdding an empty column to a DataFrameAdding column to DataFrame with constant valuesAdding new columns to a DataFrameAppending rows to a DataFrameApplying a function that takes as input multiple column valuesApplying a function to a single column of a DataFrameChanging column type to categoricalChanging the name of a DataFrame's indexChanging the order of columns in a DataFrameChanging the type of a DataFrame's indexChanging the type of a DataFrame's columnChecking if a column exists in a DataFrameChecking if a DataFrame column contains some valuesChecking if a value exists in a DataFrame in PandasChecking if column is numericChecking the data type of columnsChecking whether column values match or contain a patternCombining two columns as a single column of tuplesCombining two columns of type string in a DataFrameComputing the average of columnsComputing the correlation between columnsConcatenating DataFrames horizontallyConcatenating DataFrames verticallyConverting a row to column labelsConverting categorical type to intConverting column to listConverting Index to listConverting percent strings into numericConverting the index of a DataFrame into a columnCounting duplicate rowsCounting number of rows with no missing valuesCounting the occurrence of values in columnsCounting unique values in a column of a DataFrameCounting unique values in rows of a DataFrameCreating a new column based on other columnsCreating new column using if, elif and elseDescribing certain columnsDropping columns whose label contains a substringGetting column values based on another column values in a DataFrame in PandasGetting columns as a copyGetting columns whose label contains a substringGetting maximum value in columnsGetting maximum value of entire DataFrameGetting mean of columnsGetting median of columnsGetting minimum value in columnsGetting row label when calling applyGetting row labels as listGetting rows where column value contains any substring in a listGetting the name of indexGetting type of indexGrouping DataFrame rows into listsInserting column at a specific locationIterating over each column of a DataFrameIterating over each row of a DataFrameModifying rows of a DataFrameModifying values in IndexRemoving columns from a DataFrameRemoving columns using column labelsRemoving columns using integer indexRemoving columns with all missing valuesRemoving columns with some missing valuesRemoving duplicate columnsRemoving duplicate rowsRemoving first n rows of a DataFrameRemoving multiple columnsRemoving prefix from column labelsRemoving rows at random without shufflingRemoving rows from a DataFrame based on column valuesRemoving rows using integer indexRemoving rows with all zerosRemoving suffix from column labelsRenaming columns of a DataFrameReplacing substring in column valuesReturning multiple columns using the apply functionReversing the order of rowsSetting a new index of a DataFrameSetting an existing column as the new indexSetting column as the indexSetting integers as column labelsShowing all column labelsShuffling the rows of a DataFrameSorting a DataFrame by columnSorting a DataFrame by indexSorting DataFrame alphabeticallySorting DataFrame by column labelsSplitting a column of strings into multiple columnsSplitting column of lists into multiple columnsSplitting dictionary into separate columnsStripping substrings from values in columnsStripping whitespace from columnsStripping whitespaces in column labelsSumming a column of a DataFrameSumming rows of specific columnsSwapping the rows and columns of a DataFrameUnstacking certain columns onlyUpdating a row while iterating over the rows of a DataFrameUpdating rows based on column valuesUsing apply method in parallel
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

Updating rows based on column values in Pandas DataFrame

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Filling rows where condition is based on their values with a constant

Consider the following DataFrame:

df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]}, index=["a","b","c"])
df
A B C
a 1 4 7
b 2 5 8
c 3 6 9

To fill rows where value for column A is 1 or value for column C is greater than or equal to 9:

df.loc[(df["A"] == 1) | (df["C"] >= 9)] = 0
df
A B C
a 0 0 0
b 2 5 8
c 0 0 0

Here, we are first extracting the following Series of booleans:

(df["A"] == 1) | (df["C"] >= 9)
a True
b False
c True
dtype: bool

Passing in this boolean mask into the loc property will return the rows that correspond to True. We then fill these rows with the value 0 using standard assignment (=).

Filling certain row values where condition is based on their values with a constant

Consider the following DataFrame:

df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]}, index=["a","b","c"])
df
A B C
a 1 4 7
b 2 5 8
c 3 6 9

Instead of filling the entire rows with a constant, you can specify which rows to fill like so:

df.loc[(df["A"] == 1) | (df["C"] >= 9), "B"] = 0
df
A B C
a 1 0 7
b 2 5 8
c 3 0 9

Here, the "B" after the comma indicates that we want to only update column B, and leave the other column values intact.

Filling rows where condition is based on a function of their values

Consider the following DataFrame:

df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]}, index= ["a","b","c"])
df
A B C
a 1 4 7
b 2 5 8
c 3 6 9

To fill rows where the sum of the value for column A and the value for column B is greater than 6:

def criteria(my_df):
return my_df["A"] + my_df["B"] > 6

df.loc[criteria] = 0
df
A B C
a 1 4 7
b 0 0 0
c 0 0 0

To clarify, criteria(my_df) takes in as argument the source DataFrame, and returns a Series of booleans where True corresponds to the rows that satisfy the condition:

def criteria(df):
print(df["A"] + df["B"] > 6)
return df["A"] + df["B"] > 6

df.loc[criteria] = 0
a False
b True
c True
dtype: bool

The loc property will then return all the rows that correspond to True in this boolean mask.

Filling rows using a function of their values

Consider the following DataFrame:

df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]}, index= ["a","b","c"])
df
A B C
a 1 4 7
b 2 5 8
c 3 6 9

To double the values of rows where the value for column B is larger than 4:

df.loc[df["B"] > 4] = df * 2
df
A B C
a 1 4 7
b 4 10 16
c 6 12 18

Here, loc returns all the rows where the value for column B is larger than 4. These rows are then assigned new values using =. Note that the assignment only updates the rows returned by loc, and so the rows that do not satisfy the condition will be kept intact.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...