Multiplying all values ββin Pandas Dataframe rows
It's basically a data file:
col1 col2 col3 label
row1 1 0 1 1
row2 0 0 0 1
row3 1 1 1 0
row4 1 2 1 0
I basically need it to go down each line, and if label = 0, multiply all the values ββin the line by -1.
I've tried many different approaches, including:
df.ix[3] = df.ix[3].multiply(-1)
Which returns:
SettingWithCopyWarning: The value is trying to be set on a copy of the slice from the DataFrame. Try using .loc [row_indexer, col_indexer] =
I also tried deleting the row and replacing, which doesn't work because the indices are changing.
Alternatively, you can run apply
for row operations:
df = df.apply(lambda row: row*-1 if row['label'] == 0 else row, axis=1)
print(df)
# col1 col2 col3 label
# row1 1 0 1 1
# row2 0 0 0 1
# row3 -1 -1 -1 0
# row4 -1 -2 -1 0
In [156]: df.loc[df.label==0, df.columns.drop('label')] = \
df.loc[df.label==0, df.columns.drop('label')].mul(-1)
In [157]: df
Out[157]:
col1 col2 col3 label
row1 1 0 1 1
row2 0 0 0 1
row3 -1 -1 -1 0
row4 -1 -2 -1 0
or a shorter version:
In [160]: df.loc[df.label==0, df.columns.drop('label')] *= -1
In [161]: df
Out[161]:
col1 col2 col3 label
row1 1 0 1 1
row2 0 0 0 1
row3 -1 -1 -1 0
row4 -1 -2 -1 0
One approach using broadcasting
and masking
mainly exploiting the fact that multiplication 0
by -1
will not change 0
so that we can multiply all strings by -1
that have corresponding values label
like 0s
-
df[(df.label==0)] *= -1
Example run -
In [70]: df
Out[70]:
col1 col2 col3 col4 label
row1 1 0 1 3 1
row2 0 0 0 2 1
row3 1 1 1 5 0
row4 1 2 1 7 0
In [71]: df[(df.label==0)] *= -1
In [72]: df
Out[72]:
col1 col2 col3 col4 label
row1 1 0 1 3 1
row2 0 0 0 2 1
row3 -1 -1 -1 -5 0
row4 -1 -2 -1 -7 0