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

2024-06-09 00:02:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 数据indataframedfoutonelistpd
2条回答

可以使用.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

相关问题 更多 >