Update values ​​in DF based on column names

WBOY
Release: 2024-02-09 13:00:15
forward
571 people have browsed it

根据列名更新 DF 中的值

Question content

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
...
Copy after login

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]
Copy after login

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
...
Copy after login


Correct answer


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
Copy after login

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!