简体   繁体   中英

Pandas select all columns from m to n and replace values on a condition

I have a pandas dataframe looking like:

df=pd.DataFrame([list('abcd'),list('efgh'),list('ijkl'),list('mnop')],
              columns=['one','two', 'three', 'four'])

In [328]: df
Out[328]:     
    one   two  three   four
0     a      b     c      d
1     e      f     g      h
2     i      j     k      l
3     m      n     o      p

And I would like to select columns 1 to 3, (more generally columns n through to m) and replace all 'h' with '1' and 'k' with '2' for example. How can I achieve this?

Result:

In [328]: df
Out[328]:     
    one   two  three   four
0     a      b     c      d
1     e      f     g      1
2     i      j     2      l
3     m      n     o      p

You can use .iloc to numerically index your dataframe, apply a function to replace the values for each cell, then save that output back to the original dataframe

d = {'h':1, 'k':2}
df.iloc[:,1:4] = df.iloc[:,1:4].applymap(lambda x: d[x] if x in d else x)

df
# returns
  one two three four
0   a   b     c    d
1   e   f     g    1
2   i   j     2    l
3   m   n     o    p

Let's try this:

df2 = df.assign(**df.iloc[:,1:4].replace({'h':'1','k':2}))
print(df2)

Output:

   one two three four
0   a   b     c    d
1   e   f     g    1
2   i   j     2    l
3   m   n     o    p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM