Pandas:根据行内容选择列

2024-04-20 00:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有以下数据帧:

        Col1     Col2    Col3    Col4   Col5
Index
Row1    Code1   Code2   Code3  Code4  Code5
Row2    1       0       1       1       0
Row3    10      0       10      0       10
Row4    7070    56746   87647   969     687876
Row5    98798   79657   6876    977     6678

有没有办法根据行(索引)的条件选择列

那么比如说,

for all columns with Row2==1:
    do something with all the rows in those columns

同样地

for all columns with Row3==0:
    do something with all the rows in those columns

等等

我在想

for "Row3" in df.index:
    if "Row3" == 0:
        # Do certain calculation

Tags: columnsthe数据inforwithalldo
1条回答
网友
1楼 · 发布于 2024-04-20 00:09:36

使用^{}

m2 = df.loc['Row2'].eq(1)
#m2 = df.loc['Row2'].eq('1') #if string type

cols_Row2 = df.columns[m2]
#Index(['Col1', 'Col3', 'Col4'], dtype='object')

#for col in cols_Rows2:
    #.....

为数据帧编制索引

df.loc[:,m2] 
#         Col1    Col3    Col4
#Index                        
#Row1    Code1   Code3   Code4 
#Row2        1       1       1
#Row3       10      10       0
#Row4     7070   87647     969
#Row5    98798    6876     977

相关问题 更多 >