2024-06-30 16:05:45 发布
网友
1 0 0 0 1 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1
我有一个数据帧(见上文)。我需要比较它的行以得到匹配的行。所以对于上面的数据,我应该在比较后得到row1=row4=row6和row2=row5。在python中有没有有效的方法来进行行比较呢。在
下面是我的想法。在
import pandas as pd df = pd.DataFrame({0: {0: 1, 1: 0, 2: 0, 3: 1, 4: 0, 5: 1}, 1: {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0}, 2: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 4: {0: 1, 1: 0, 2: 1, 3: 1, 4: 0, 5: 1}}) groups = df.groupby(df.columns.tolist()) df.loc[:, 'group_num'] = None for num, group in enumerate(groups): df.loc[group[1].index, 'group_num'] = num
收益率。。。在
为什么第[1]组在最后一行?在
因为您正在迭代一个形式为(group_name,group_table)的元组。组[1]访问实际分组的数据帧。在
使用:
import pandas as pd df = pd.DataFrame({0: {0: 1, 1: 0, 2: 0, 3: 1, 4: 0, 5: 1}, 1: {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0}, 2: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 4: {0: 1, 1: 0, 2: 1, 3: 1, 4: 0, 5: 1}}) print df 0 1 2 3 4 0 1 0 0 0 1 1 0 0 0 0 0 2 0 1 0 0 1 3 1 0 0 0 1 4 0 0 0 0 0 5 1 0 0 0 1
#print groups for i, g in df.groupby((~((df2 == df2.shift(1)).all(1))).cumsum()): print g 0 1 2 3 4 1 0 0 0 0 0 4 0 0 0 0 0 0 1 2 3 4 0 1 0 0 0 1 3 1 0 0 0 1 5 1 0 0 0 1 #dict comprehension for storing groups dfs = {i-1: g for i,g in df.groupby((~((df2 == df2.shift(1)).all(1))).cumsum())} print dfs {0.0: 0 1 2 3 4 1 0 0 0 0 0 4 0 0 0 0 0, 1.0: 0 1 2 3 4 0 1 0 0 0 1 3 1 0 0 0 1 5 1 0 0 0 1} print dfs[0] 0 1 2 3 4 1 0 0 0 0 0 4 0 0 0 0 0 print dfs[1] 0 1 2 3 4 0 1 0 0 0 1 3 1 0 0 0 1 5 1 0 0 0 1
下面是我的想法。在
收益率。。。在
^{pr2}$为什么第[1]组在最后一行?在
因为您正在迭代一个形式为(group_name,group_table)的元组。组[1]访问实际分组的数据帧。在
使用:
^{pr2}$相关问题 更多 >
编程相关推荐