熊猫根据行信息选择列名

时间:2018-10-25 05:52:22

标签: pandas python-3.5

我正在使用Pandas和Python 3.5.1。

请假定以下数据框名为df

    name1  name2  name3  name4
0     1      2      3      4
1     5      6      7      8
2     4      9      6      2
3     5      1      7      3

请注意,每一行中的所有值都是唯一的,没有一行的行与另一行的值相同。

说我眼中有一个数字,例如7中的df[name3][1]。有没有一种方法可以根据行name3和值(1)只获得列标题(7)

我不希望列本身有任何内容,例如3, 7, 6, or 7。我只想要列标题。

3 个答案:

答案 0 :(得分:1)

一般解决方案-如果不匹配rowval,则可以正常工作:

val = 70
row = 10

val = df.reindex(index=[row]).eq(val).squeeze()
col = next(iter(val.index[val]), 'no match')
print (col)
no match

另一种通用解决方案:

def get_col(row, val):
    try:
        a = df.loc[row].eq(val)
        c = a.index[a][0]
    except KeyError:
        c = 'not matched row'
    except IndexError:
        c = 'not matched value'
    return c

print (get_col(1, 7))
name3
print (get_col(10, 7))
not matched row
print (get_col(1, 70))
not matched value
print (get_col(10, 70))
not matched row

如果总是存在val DataFrame中存在行值的解决方案,因为如果不存在并且从df.loc[row].eq(val)返回所有False,则idxmax首先返回{{ 1}}-第一列名称。

False

说明

首先通过DataFrame.loc选择行:

val = 7
row = 1
col = df.loc[row].eq(val).idxmax()
#if want seelct by pocition use iloc
#col = df.iloc[row].eq(val).idxmax()
print (col)
name3

然后用eq

进行比较
print (df.loc[row])
name1    5
name2    6
name3    7
name4    8
Name: 1, dtype: int64

最后得到idxmax的第一个print (df.loc[row].eq(val)) name1 False name2 False name3 True name4 False Name: 1, dtype: bool 的索引值:

True

答案 1 :(得分:0)

您可以使用map方法获取所需的内容。 例如:

maps = [[],[(0,'name1'),(3,'name2')],[(0,'name2'),(2,'name4')],... ]

当您选择1 from df[name1][0]时,您会发现maps[1] = [(0,'name1'),(3,'name2')],并且可以获得row = 0name1的列名

整个代码如下:

maps = [(),() ..... ]
for col in data.columns:
    for row in range(len(data)):
        value = data[col][row]
        maps[value] = (row,col)

答案 2 :(得分:0)

另一种选择是遍历键,值并使用next。

lookup = 14
row = 1
next((k for k,v in df.iloc[row,:].items() if v == lookup), 'No match')