这是我的数据框架,它有高维(大量的列)超过10000列
“我的数据”中的列分为3类
列以“基本”开头 列以“\u T”结尾 还有其他一切
我的数据帧示例如下
RowID Basic1011 Basic2837 Lemon836 Car92_T Manf3953 Brat82 Basic383_T Jot112 ...
1 2 8 4 3 1 5 6 7
2 8 3 5 0 9 7 0 5
我希望在我的数据框中包含所有“基本”和;“_T”列,并且只有其他列的前N个(变量可以是3、5、10、100等)
我有这个代码为所有列提供top N。但我要找的只是列的前N个,而不是“基本”或“T”
我指的是最高价值
Top = 20
df = df.where(df.apply(lambda x: x.eq(x.nlargest(Top)), axis=1), 0)
我怎样才能做到这一点
尝试类似的方法,您可能需要在一开始就使用列选择来确保正确过滤
步骤1:您可以使用^{} 和regex来过滤具有以下两个条件的列:
使用的正则表达式是
r'(?:^Basic)|(?:_T$)'
,其中:(?: )
是正则表达式的非捕获组。它用于临时分组^
是文本锚点的开始,用于指示文本的开始位置Basic
与文本Basic
匹配(与^
一起,此Basic
必须位于列标签的开头)|
是or
的正则表达式元字符_T
匹配文本_T
$
是文本锚的结尾,用于指示文本位置的结尾(与列名末尾的_T
、_T$
一起指示_T
)我们将这些列命名为
cols_Basic_T
步骤2:然后,使用^{} 查找其他列。我们将这些其他列命名为
cols_others
。第3步:然后,我们对这些选定列上的所有列
col_others
应用类似的代码,该代码用于为您提供top N全套代码:
结果:
cols\u Basic\u T
cols\u其他人
df_其他人
相关问题 更多 >
编程相关推荐