热线电话:13121318867

登录
2019-03-01 阅读量: 642
根据完整的数据框对一个不完整的数据框进行排序

我有两个数据帧用于分类问题。df_x(数据,未完成的拼图,未填充位置的零)和df_y(标签,完成的拼图)。

数据帧有几十万行,因此效率很重要。

问题是我没有保证df_x的第i个索引对应于df_y的第i个索引。我想修复数据帧,以便它们的索引匹配。

我有这个非常低效的实现,但是我无法保留它。

x2y = [].

no_label = []

for i in df_x.index:

a = df_x[i:i+1] #receives one line of df_x at a time.

a = a.loc[:, (a != 0).any(axis=0)] #excludes the zeros (unfilled parts of the puzzle)

match = True

for j in df_y.index: #loops over all lines of df_y

for a_i in a:

if (a[0:1][a_i].item() != df_y[j:j+1][a_i].item()):

match = False #if one element is not present in the final solution, than it goes to the next line in df_y

break

if match:

x2y.append((i,j))

df_y[i:i+1] = df_y[j:j+1] #replace label at the position of interest

break

if not match:

no_label.append(i) #unsolved puzzles with no label

这就是数据帧的样子:

df_x.head()

0 1 2 3 4 5 ... 75 76 77 78 79 80

0 0.0 0.0 0.0 0.0 0.0 168.0 ... 0.0 0.0 886.0 0.0 0.0 973.0

1 0.0 0.0 0.0 0.0 0.0 168.0 ... 0.0 0.0 886.0 899.0 0.0 973.0

2 0.0 0.0 0.0 0.0 0.0 168.0 ... 0.0 0.0 886.0 899.0 0.0 973.0

3 0.0 0.0 0.0 0.0 0.0 168.0 ... 0.0 0.0 886.0 899.0 0.0 973.0

4 0.0 0.0 0.0 149.0 0.0 168.0 ... 0.0 0.0 886.0 899.0 0.0 973.0

[5 rows x 81 columns]

df_y.head()

Out[59]:

0 1 2 3 4 ... 76 77 78 79 80

0 112.0 126.0 137.0 149.0 154.0 ... 956.0 961.0 973.0 982.0 997.0

1 112.0 126.0 137.0 149.0 154.0 ... 956.0 961.0 973.0 982.0 997.0

2 112.0 126.0 137.0 149.0 154.0 ... 956.0 961.0 973.0 982.0 997.0

3 112.0 126.0 137.0 149.0 154.0 ... 956.0 961.0 973.0 982.0 997.0

4 112.0 126.0 137.0 149.0 154.0 ... 956.0 961.0 973.0 982.0 997.0

解决办法:如果您认为大多数匹配,您可以通过运行来解决那些问题

matches = ((df_x == df_y) | (df_x == 0)).all(axis=1)

这也是同样的事情,但同时在整个数据框架上。它将返回一系列布尔值,对应于每一行是否df_x匹配相应的行df_y。然后你可以对那些没有的那些进行分类。

df_x[matches]将只是匹配的行,或df_x[~matches]将是那些不匹配的行。

[5 rows x 81 columns]

0.0000
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子