Py学习  »  Python

在python中分组并打印数据帧中的最大值

mmmaaraaa • 3 年前 • 1222 次点击  

数据帧有3列

    A                   B          C      
^0hand(%s)leg$        27;30       42;54
^-(%s)hand0leg        39;30       47;57
^0hand(%s)leg$        24;33       39;54

所以A列有这样的正则表达式模式,如果这些模式是相似的,例如现在第1行和第3行是相似的,所以它必须合并这两行,只输出最大值,如下所示:

输出:

 A                   B          C      
^0hand(%s)leg$        27;33       42;54
^-(%s)hand0leg        39;30       47;57

任何线索都会有帮助

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129400
 
1222 次点击  
文章 [ 1 ]  |  最新文章 3 年前
mozway
Reply   •   1 楼
mozway    3 年前

你可以使用:

(df.set_index('A').stack()
   .str.extract('(\d+);(\d+)').astype(int)
   .groupby(level=[0,1]).agg(max).astype(str)
   .assign(s=lambda d: d[0]+';'+d[1])['s']    # OR # .apply(';'.join, axis=1)
   .unstack(1)
   .loc[df['A'].unique()]  ## only if the order of rows matters
   .reset_index()
)

输出:

                A      B      C
0  ^0hand(%s)leg$  27;33  42;54
1  ^-(%s)hand0leg  39;30  47;57