获取切片列值

2024-10-01 13:24:19 发布

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

我和你一起工作虹膜鳞片用于分析目的的数据集。但在处理过程中,如何在读取数据文件后获得切片列值

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

Tags: 文件csv数据目的dfread切片读取数据
3条回答

在给熊猫喂食之前对数据进行预处理,去除多余的数据

import re, io
with open("../Data/iris.scale.csv") as f:
    data = f.read()

p = r'[1-4]:'
data = re.sub(p, '', data)

然后,您可以在将数据馈送给Pandas之前将其写入新文件,或者将其放入类似文件的对象中,然后将其馈送给Pandas。你知道吗

#Python 2.7
data = io.BytesIO(data)
#Python 3x
#data = io.StringIO(data)
df = pd.read_csv(data, delim_whitespace = True, index_col = False, names=['class','S.lenght','S.width','P.lenght','P.width'])

您可以使用^{}来创建DataFrame,其中值只有:^{}提取,最后一次转换输出到float

df=df.set_index('class').apply(lambda x: x.str.split(':').str[1]).astype(float).reset_index()
print (df)
   class  S.lenght   S.width  P.lenght   P.width
0      1 -0.555556  0.250000 -0.864407 -0.916667
1      1 -0.666667 -0.166667 -0.864407 -0.916667
2      1 -0.833333 -0.083330 -0.830508 -0.916667

另一个带有^{}的解决方案:

df = df.set_index('class').apply(lambda x: x.str.extract(':(.*)', expand=False)).astype(float).reset_index()
print (df)
   class  S.lenght   S.width  P.lenght   P.width
0      1 -0.555556  0.250000 -0.864407 -0.916667
1      1 -0.666667 -0.166667 -0.864407 -0.916667
2      1 -0.833333 -0.083330 -0.830508 -0.916667

pandas

  • filter关注正确的列
  • stack+str.split+unstack
  • update

代码

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

  • split一次完成整个数组
  • 构造新数组
  • 切片和分配

代码

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

相关问题 更多 >