Python 选择从m到n的所有列,并根据条件替换值

Python 选择从m到n的所有列,并根据条件替换值,python,pandas,Python,Pandas,我有一个熊猫数据框,看起来像: 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

我有一个熊猫数据框,看起来像:

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
我想选择第1列到第3列(通常是第n列到第m列),并用“1”替换所有的“h”,用“2”替换所有的“k”。 我怎样才能做到这一点

结果:

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

您可以使用
.iloc
对数据帧进行数字索引,应用函数替换每个单元格的值,然后将输出保存回原始数据帧

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

您可以使用
.iloc
对数据帧进行数字索引,应用函数替换每个单元格的值,然后将输出保存回原始数据帧

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
让我们试试这个:

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

   one two three four
0   a   b     c    d
1   e   f     g    1
2   i   j     2    l
3   m   n     o    p
让我们试试这个:

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

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

你想要列“1”、“2”和“3”还是零索引列从1到3(即列“2”、“3”和“4”)?@James我想要零索引列1到3(列标记为“2”、“3”和“4”),你想要列“1”、“2”和“3”还是零索引列从1到3(即列“2”“,“三”和“四”)?@James我想要零索引列1到3(列标记为“二”、“三”和“四”)