如何使用Python为转置数据帧中的每个单元实现if-else语句



我是Python的新手
在使用Pandas转换.csv原始文件后,我不知道如何为每个数据合并if-else语句。

我使用Pandas转置的数据:

Voltage 0.2V 0.4V 0.6V 0.8V 1V 1.2V
Point A 0 15 100 5000 300 50
Point B 10000 4000 500 10 0 0
Point C 0 10 40 200 400 1000

A点、B点和C点的每个数据中的预期条件语句;C

If (data = 0){
State = 0;
}
elsif (data >0 and data <= 10){
State = 1;
}
elsif (data >10 and data <= 100){
State = 2;
}
elsif (data >100 and data <= 1000){
State = 3;
}
elsif (data >1000 and data <= 10000){
State = 4;
}
else {
State = "Invalid";
}

我的预期输出:

Voltage 0.2V 0.4V 0.6V 0.8V 1V 1.2V
Point A 0 2 2 4 3 2
Point B 4 4 3 1 0 0
Point C 0 1 2 3 3 3

通过DataFrame.stackcut与转换后的系列DataFrame一起使用,通过cat.add_categories添加缺失类别,并通过Series.unstack:重塑

print (df)
Voltage    0.2V  0.4V  0.6V  0.8V   1V  1.2V
0  Point A  100000    15   100  5000  300    50 <-changed first value for invalid
1  Point B   10000  4000   500    10    0     0
2  Point C       0    10    40   200  400  1000
df = df.set_index('Voltage')
s = pd.cut(df.stack(),
bins=[-np.inf, 0,10,100,1000,10000], 
labels=[0, 1,2,3,4], 
right=True)
s = s.cat.add_categories(['Invalid'])
df1 = s.unstack().fillna('Invalid')
print (df1)
0.2V 0.4V 0.6V 0.8V 1V 1.2V
Voltage                                
Point A  Invalid    2    2    4  3    2
Point B        4    4    3    1  0    0
Point C        0    1    2    3  3    3

最新更新