I am new in Python (I am using Python 3.6).
I have a pandas dataframe that looks like following:
import pandas as pd
data_exp = [['no', 2,1.5,3], ['exp', 2,1.5,3], ['no', 2,1.5,5]]
df = pd.DataFrame(data, columns = ['Type', 'V1','V2','V3'])
df
What I want to do is the following:
if type
in the first column of the database is equal to exp
, then I want to exp()
all the values on the same row from column 2 to the last one. If else, simply do not change the values in the other columns.
So the output would be:
data = [[2,1.5,3], [7.39,4.48,20.09], [2,1.5,5]]
Any idea how to do it? The function np.exp(df.iloc[i,1:])
for each value of i in the row numbering does not work.
CodePudding user response:
Use DataFrame.iloc
for both sides with boolean mask - compare values by exp
in Type
column, converting mask to numpy array is for prevent NotImplementedError: iLocation based boolean indexing on an integer type is not available
:
m = df['Type'].eq('exp').to_numpy()
#for oldier pandas version
m = df['Type'].eq('exp').values
df.iloc[m,1:] = np.exp(df.iloc[m,1:])
print(df)
Type V1 V2 V3
0 no 2.000000 1.500000 3.000000
1 exp 7.389056 4.481689 20.085537
2 no 2.000000 1.500000 5.000000