使用已知列值更改pandas DataFrame的多列中的值

Zix*_*ang 6 python pandas

假设我有一个这样的数据帧:

Knownvalue    A    B    C    D    E    F    G    H
  17.3413     0    0    0    0    0    0    0    0
  33.4534     0    0    0    0    0    0    0    0
Run Code Online (Sandbox Code Playgroud)

我想做的是当Knownvalue在0-10之间时,A从0变为1.当Knownvalue在10-20之间时,B从0变为1,依此类推.

更改后应该是这样的:

Knownvalue     A    B    C    D    E    F    G    H
   17.3413     0    1    0    0    0    0    0    0
   33.4534     0    0    0    1    0    0    0    0
Run Code Online (Sandbox Code Playgroud)

有谁知道如何应用方法来改变它?

Ale*_*der 5

我首先将Knownvalue系列打包成一个整数列表,其等于截断值除以10(例如27.87 // 10 = 2).这些桶表示所需列位置的整数.因为Knownvalue它在第一列中,所以我在这些值中添加一个.

接下来,我枚举这些bin值,这些值有效地为我提供了行和列整数索引的元组对.我iat用来设置这些位置的值等于1.

import pandas as pd
import numpy as np

# Create some sample data.
df_vals = pd.DataFrame({'Knownvalue': np.random.random(5) * 50})
df = pd.concat([df_vals, pd.DataFrame(np.zeros((5, 5)), columns=list('ABCDE'))], axis=1)

# Create desired column locations based on the `Knownvalue`.
bins = (df.Knownvalue // 10).astype('int').tolist()
>>> bins
[4, 3, 0, 1, 0]

# Set these locations equal to 1.
for idx, col in enumerate(bins):
    df.iat[idx, col + 1] = 1  # The first column is the `Knownvalue`, hence col + 1

>>> df
   Knownvalue  A  B  C  D  E
0   47.353937  0  0  0  0  1
1   37.460338  0  0  0  1  0
2    3.797964  1  0  0  0  0
3   18.323131  0  1  0  0  0
4    7.927030  1  0  0  0  0
Run Code Online (Sandbox Code Playgroud)