Python循环函数,仅当Dataframe中的行中满足条件时才提取第一个列名

2024-09-30 20:19:16 发布

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

我有大量的行和列的数据帧。我试图写一个循环,它将检查所有行的特定条件,当为true时,只返回我的第一个列名。我需要在新的Dataframe中存储列名和值

dataframe将如下所示:


         col1  col2  col3  col6  col7  col8  col9
Name                                             
John        0    23     0     1     4     1    23
victor      1     4     5     2     1     4    15
Alida       1     1     2     6     0     2     2
Natalie     0     1     1     4     2     3     4
Morman      3     3     1     0     5     2     1

我试图为每个大于或等于4的值获取第一个列名,结果将存储在Dataframe df2中,类似于

Name       Greater Than 4
John       col2
victor     col2
Alida      col6
Natalie    col6
Morman     col7

我是python新手。我正在尝试以下代码:

df2["Name"]=df1["Name"]
for index, row in df.iterrows():
    if df.iloc[:,[index]] >=4:
        df2["Greater Than 4"]=df.iloc[:,[index]]

Tags: namedataframedfindexjohncol2df2than
2条回答

data.csv:

Name col1 col2 col3 col6 col7 col8 col9
John 0 23 0 1 4 1 23
victor 1 4 5 2 1 4 15
Alida 1 1 2 6 0 2 2
Natalie 0 1 1 4 2 3 4
Morman 3 3 1 0 5 2 1

代码:

import pandas as pd

df = pd.read_csv('data.csv', delimiter=' ')
df = df.set_index('Name')
print(df, '\n')

for index, row in df.iterrows():
    print(index, row[row >= 4].index[0])

输出:

         col1  col2  col3  col6  col7  col8  col9
Name
John        0    23     0     1     4     1    23
victor      1     4     5     2     1     4    15
Alida       1     1     2     6     0     2     2
Natalie     0     1     1     4     2     3     4
Morman      3     3     1     0     5     2     1

John col2
victor col2
Alida col6
Natalie col6
Morman col7

如果至少有一个值大于或等于4,请将^{}^{}一起使用:

s = df.ge(4).idxmax(axis=1)
print (s)
John       col2
victor     col2
Alida      col6
Natalie    col6
Morman     col7
dtype: object

如果不确定,则可能存在不正确的输出添加^{}^{}测试:

print (df)
         col1  col2  col3  col6  col7  col8  col9
John        0     0     0     1     1     1     2
victor      1     4     5     2     1     4    15
Alida       1     1     2     6     0     2     2
Natalie     0     1     1     4     2     3     4
Morman      3     3     1     0     5     2     1


print (df.ge(4).idxmax(axis=1))
John       col1 <- incorrect value, because no match
victor     col2
Alida      col6
Natalie    col6
Morman     col7
dtype: object

mask = df.ge(4)
s = mask.idxmax(axis=1).where(mask.any(axis=1), 'no match')
print (s)
John       no match
victor         col2
Alida          col6
Natalie        col6
Morman         col7
dtype: object

最后一个数据帧使用:

df2 = s.reset_index(name='Greater Than 4')

对于最大值和最大列名,可以使用:

df2 = df.where(df.ge(4)).agg(['max','idxmax'], axis=1)
print (df2)
        max idxmax
John     23   col2
victor   15   col9
Alida     6   col6
Natalie   4   col6
Morman    5   col7

相关问题 更多 >