简体   繁体   English

如何从 Python 中的 3 行矩阵中过滤行和列?

[英]How do i filter row and column from a 3 row matrix in Python?

enter image description here在此处输入图像描述

How do I filter so that row 2 is == '1' and find the min value in row 1. And it prints the column its in?如何过滤以使第 2 行 == '1' 并在第 1 行中找到最小值。并打印其所在的列?

So in this case the result would only bring up Driver 3 [.941, 0.210, 1] because row 2 is 1 and row1 is smaller than the rest of that would also have '1' in row 2.因此,在这种情况下,结果只会显示 Driver 3 [.941, 0.210, 1],因为第 2 行是 1,并且第 1 行小于 rest,它在第 2 行中也有“1”。

When I try np.amin(df, axis=2) I get the min values i want but row 2 returns a 0 instead of 1.当我尝试 np.amin(df, axis=2) 时,我得到了我想要的最小值,但第 2 行返回 0 而不是 1。

You first need to select the subset of columns you're interested in, then find from those the minimum value, then figure out which column its in (or both at once with argmin ).您首先需要 select 您感兴趣的列的子集,然后从中找到最小值,然后找出它在哪一列(或同时使用argmin )。 (Note that pandas API somewhat prefers filtering out rows vs columns.) (请注意, pandas API 在某种程度上更喜欢过滤掉行而不是列。)

First setup some example data首先设置一些示例数据

import pandas as pd
import numpy as np
data = np.arange(24).reshape(4,6)
data[1,3:5]=1 # Adjust some values in row 2
df = pd.DataFrame(data, columns=['A', 'B', 'C', 'D', 'E', 'F'])

So transpose columns and rows所以转置列和行

dfT = df.T

Get the columns where row 2 ==1获取第 2 行 ==1 的列

dfFiltered = dfT[dfT[1] == 1]

Find the minimum row with the minimum value and get its index找到具有最小值的最小行并获取其索引

dfFiltered.index[dfFiltered[0].argmin()]

This produces 'D' for this example.这会为此示例生成'D'

First of all, for this kind of application you really want your DataFrame to be transposed.首先,对于这种应用程序,你确实希望你的 DataFrame 被转置。 It is just not convenient to filter on columns.只是在列上过滤不方便。

import pandas as pd

A = pd.DataFrame(...)
B = A.transpose()

# Now you can filter the drivers where "column" 2 is equal to 1:

C = B[B[2] == 1]

# And find where the minimum of "column" 1 is:

idx = C[1].argmin()

# Finally, find out the driver and its information:

driver = C.index[idx]
info = C.iloc[idx]
# info2 = C.loc[driver] # alternative

# To get the format you want:

print(driver, info.values)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM