pandas - 如何将所有列直接映射到pandas

标签 pandas function

这是我的数据

Id   Column_1   Column_2  Column_3
1        64.7       73.8      53.2
2        94.7       79.8      43.2

映射规则,60以下为0,60-80为1 80-100为2,所以结果为

Id   Column_1   Column_2  Column_3
1           1          1         0
2           2          1         0

问候

最佳答案

使用cut对于没有第一个列的所有列:

f = lambda x: pd.cut(x, bins=[-np.inf, 60,80, 100], labels=[0,1,2])
df.iloc[:, 1:] = df.iloc[:, 1:].apply(f)
print (df)
   Id Column_1 Column_2 Column_3
0   1        1        1        0
1   2        2        1        0

通过 reshape 实现MultiIndex Series的替代解决方案:

df = (pd.cut(df.set_index('Id').stack(),
              bins=[-np.inf, 60,80, 100], 
              labels=[0,1,2])
        .unstack())
print (df)
   Column_1 Column_2 Column_3
Id                           
1         1        1        0
2         2        1        0

另一种选择 numpy.select :

df1 = df.iloc[:, 1:]
m1 = df1.le(60)
m2 = df1.gt(60) & df1.le(80)
m3 = df1.gt(80) & df1.le(100)
df.iloc[:, 1:] = np.select([m1,m2, m3], [0,1,2])

关于pandas - 如何将所有列直接映射到pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71673839/

相关文章:

python - Pandas 检查时间序列的连续性

c++ - 基本的 if, else-if 脚本没有按预期工作

php - 为什么如果我添加额外的参数,javascript 函数不会被调用

function - Ada 函数头中的可选注释部分

c - 访问不带括号的函数指针

python - 按条件过滤 pandas

python - 如何将pandas中的堆叠数据框转换为字典?

python - 将列向量转换为多列矩阵

python - 如何根据特定条件、特定列和特定行更新数据框中的值?

c++ - 如何更改指针访问运算符的含义