DataFrame.loc multiple columns replace
See original GitHub issuePython 3.6.8 pandas==0.25.3
#! -*- coding:utf-8 -*-
import pandas as pd
df = pd.DataFrame([
{'a':'a1','b':'b1','c':'c1','d':'d1','e':'e1'},
{'a':'a2','b':'b2','c':'c2','d':'d2','e':'e2'}
])
import copy
df2 = copy.deepcopy(df)
print(df)
# a b c d e
# 0 a1 b1 c1 d1 e1
# 1 a2 b2 c2 d2 e2
df.loc[df['a']=='a2', ['c']] = df['e']
print(df)
# a b c d e
# 0 a1 b1 c1 d1 e1
# 1 a2 b2 e2 d2 e2
# loc muti columns replace has some problem
df.loc[df['a']=='a2', ['b','c']] = df[['d','e']]
print(df)
# a b c d e
# 0 a1 b1 c1 d1 e1
# 1 a2 NaN NaN d2 e2
Issue Analytics
- State:
- Created 4 years ago
- Comments:15 (15 by maintainers)
Top Results From Across the Web
Pandas update multiple columns at once - Stack Overflow
I accounted for columns by using .values at the end. ... #update for k in mp: df.loc[mask,k] = df[mp.get(k)] #swap back np.nans for...
Read more >Pandas Select Multiple Columns in DataFrame
To select the columns by names, the syntax is df.loc[:,start:stop:step] ; where start is the name of the first column to take, stop...
Read more >How to replace values in Pandas DataFrame columns?
Replace all occurrences of a value in a column; Replace one or multiple values based on a condition; Replace a cell with nan...
Read more >pandas.DataFrame.replace — pandas 1.5.2 documentation
Replace values given in to_replace with value . Values of the DataFrame are replaced with other values dynamically. This differs from updating with...
Read more >Pandas – Replace Values in Column based on Condition
To replace a values in a column based on a condition, using DataFrame.loc, use the following syntax. ... In the following program, we...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Yep I would agree with counter-intuitive. Just thought this is a nice feature, if it is not a bug:)
You’re using label-based indexing using .loc. Pandas therefore does not infer that you want to replace column b with column d and column c with column e-- that would be positional logic.
Either you can use .iloc for this use case, or else rename the columns before setting:
Alternatively you can also use the setting using .to_numpy, see the warning box at https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#basics. In this case you need to do the alignment on the right hand side yourself: