Home >Backend Development >Python Tutorial >Update values in DF based on column names
I have the next pandas dataframe:
x_1 x_2 x_3 x_4 col_to_replace cor_factor 1 2 3 4 x_2 1 3 3 5 1 x_1 6 2 2 0 0 x_3 0 ...
I want to update the name column saved in col_to_replace
with the value in cor_factor
and save the result in the corresponding column as well as the car_factor
column.
Some (ugly) solutions might be:
for i in len(df.shape[0]): df[df['col_to_replace']].iloc[i] = df[df['col_to_replace']].iloc[i] - df['cor_factor'].iloc[i] df['cor_factor'].iloc[i] = df['cor_factor'].iloc[i] - df[df['col_to_replace']].iloc[i]
This method is definitely not time-saving. I'm looking for a faster solution.
The output of df should be like this:
x_1 x_2 x_3 x_4 col_to_replace cor_factor 1 1 3 4 x_2 -1 -3 3 5 1 x_1 3 2 2 0 0 x_3 0 ...
Use pivot
to correct the x_
value and index lookup Correct the last column. Since the value changes, make sure to copy before modifying:
# perform indexing lookup # save the value for later idx, cols = pd.factorize(df['col_to_replace']) corr = df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx] # pivot and subtract the factor # ensure original order of the columns cols = df.columns.intersection(cols, sort=false) df[cols] = df[cols].sub(df.pivot(columns='col_to_replace', values='cor_factor'), fill_value=0).convert_dtypes() # correct with the saved "corr" df['cor_factor'] -= corr
Output:
x_1 x_2 x_3 x_4 col_to_replace cor_factor 0 1 1 3 4 x_2 -1 1 -3 3 5 1 x_1 3 2 2 2 0 0 x_3 0
The above is the detailed content of Update values in DF based on column names. For more information, please follow other related articles on the PHP Chinese website!