1
$\begingroup$

So I've been trying to iterate over rows of my dataframe and my goal is to find matching rows based on two particular columns (say C and P). Then i need to do some manipulations as well in the data for the rows. I've read quite a few answers here telling to use iterrows() or itertuples() but that doesnt serve my purpose because I cannot manipulate my data using them. Same goes for functions like groupby since it only allows manipulation on the whole groups not elements of those groups(correct me if I am wrong here because thats what I have seen in the articles on groupby(). What approach should I use to match rows in my data frame to each other based on columns and then manipulate them.

$\endgroup$
1
  • 2
    $\begingroup$ Can you give an example of what you are trying to achieve? Generally you want to avoid looping over rows in pandas as it's likely not the most efficient way to achieve things. $\endgroup$ – Oxbowerce Feb 12 at 13:29
0
$\begingroup$

"What approach should I use to match rows in my data frame to each other based on columns and then manipulate them."

Use pandas.DataFrame.loc:

Setting values Set value for all items matching the list of labels

df.loc[['viper', 'sidewinder'], ['shield']] = 50
df
            max_speed  shield
cobra               1       2
viper               4      50
sidewinder          7      50

Set value for rows matching callable condition

df.loc[df['shield'] > 35] = 0
df
            max_speed  shield
cobra              30      10
viper               0       0
sidewinder          0       0
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.