Skip to main content
 首页 » 编程设计

python之获取切片列值

2024年10月01日4cyq1162

我正在使用 iris.scale 数据集进行分析。但是在处理过程中,我如何在读取数据文件后获取切片列值,

df = pd.read_csv("../Data/iris.scale.csv", sep=' ', header=None, names=['class','S.lenght','S.width','P.lenght','P.width']) 
print(df.head(3)) 
 
   class     S.lenght       S.width     P.lenght      P.width 
     1        1:-0.555556    2:0.25      3:-0.864407     4:-0.916667 
     1        1:-0.666667    2:-0.166667 3:-0.864407     4:-0.916667 
     1        1:-0.833333    2:-0.08333  3:-0.830508     4:-0.916667 

但是如何得到这些切片的列,像这个没有任何特征引用的列,所以可以处理

class     S.lenght       S.width     P.lenght      P.width 
     1        -0.555556    0.25       -0.864407     -0.916667 
     1        -0.666667   -0.166667   -0.864407     -0.916667 
     1        -0.833333   -0.08333    -0.830508     -0.916667 

请您参考如下方法:

Pandas

  • 过滤以关注正确的列
  • 堆栈 + str.split + unstack
  • 更新

代码

df.update( 
    df.filter(regex='S|P').stack().str.split(':').str[1].astype(float).unstack()) 
df 
 
   class  S.lenght   S.width  P.lenght   P.width 
0      1 -0.555556      0.25 -0.864407 -0.916667 
1      1 -0.666667 -0.166667 -0.864407 -0.916667 
2      1 -0.833333  -0.08333 -0.830508 -0.916667 

numpy

  • 一次拆分整个数组
  • 构造新数组
  • 切片和赋值

代码

s = np.core.defchararray.split(df.values[:, 1:].astype(str), ':').tolist() 
df.iloc[:, 1:] = np.array(s)[:, :, 1].astype(float) 
 
   class  S.lenght   S.width  P.lenght   P.width 
0      1 -0.555556      0.25 -0.864407 -0.916667 
1      1 -0.666667 -0.166667 -0.864407 -0.916667 
2      1 -0.833333  -0.08333 -0.830508 -0.916667