定义用于更改列值和创建新数据集的函数 [英] Defining a function for changing column values and creating new datasets

查看:80
本文介绍了定义用于更改列值和创建新数据集的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个函数,该函数将采用一个数据框并更改列中的值以创建多个新数据框.

I am trying to define a function where it will take a dataframe and change values in a column to create multiple new dataframes.

以df1为例,如下所示:

As an example, from df1 looking like:

df1:

  class    colB    colC
0   1      1b      1c
1   2      2b      2c
2   3      3b      3c
3   4      4b      4c
4   5      5b      5c

我正在尝试创建多个二进制类来实现一对一分类.因此该函数将创建...

I am trying to create multiple binary classes to implement one-vs-all classification. So the function would create...

df2:
  class    colB    colC
0   1      1b      1c
1   -1      2b      2c
2   -1      3b      3c
3   -1      4b      4c
4   -1      5b      5c

df3:
  class    colB    colC
0   -1      1b      1c
1    1      2b      2c
2   -1      3b      3c
3   -1      4b      4c
4   -1      5b      5c

df4:
  class    colB    colC
0   -1      1b      1c
1   -1      2b      2c
2    1      3b      3c
3   -1      4b      4c
4   -1      5b      5c

,依此类推.所有唯一值都是1到120之间的增量值.

and so on. All the unique values are an incremental value ranging from 1 to 120.

有什么想法吗?

谢谢

推荐答案

使用np.identity(我将列名更改为class_,因此它没有使用受保护的关键字):

Using np.identity (I changed your column name to class_ so it's not using a protected keyword):

arr = np.identity(len(df1))
arr[arr==0] = -1

dfs = [df1.assign(class_=arr[:, i]) for i in range(len(df1))]

for d in dfs:
    print(d, end='\n\n')

   class_ colB colC
0     1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1     1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2     1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3     1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4     1.0   5b   5c

这篇关于定义用于更改列值和创建新数据集的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆