F.D*_*F.D 5 python indexing pandas
任务:在多列数据框中搜索一个值(所有值都是唯一的)并返回该行的索引。
当前:使用get_loc,但似乎只允许一次传递单个列,从而导致除try语句之外的一组无效记录。虽然有效,但是有人知道这样做的更有效方法吗?
df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))
try:
unique_index = pd.Index(df['A'])
print(unique_index.get_loc(20))
except KeyError:
try:
unique_index = pd.Index(df['B'])
print(unique_index.get_loc(20))
except KeyError:
unique_index = pd.Index(df['C'])
print(unique_index.get_loc(20))
Run Code Online (Sandbox Code Playgroud)
循环似乎不起作用,因为如果一列不包含值,则会引发KeyError。我看过诸如.contains或.isin之类的函数,但这是我感兴趣的位置索引。
您可以使用np.where,它返回您的值所在的行和列索引的元组。然后,您可以仅从中选择行。
df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))
indices = np.where(df.values == 20)
rows = indices[0]
if len(rows) != 0:
print(rows[0])
Run Code Online (Sandbox Code Playgroud)
考虑这个例子而不是使用 np.random.seed
np.random.seed([3, 1415])
df = pd.DataFrame(
np.random.randint(200 ,size=(4, 4)),
columns=list('ABCD'))
df
A B C D
0 11 98 123 90
1 143 126 55 141
2 139 141 154 115
3 63 104 128 120
Run Code Online (Sandbox Code Playgroud)
我们可以找到您要使用np.where和切片的值。请注意,我使用了一个值,55因为这是我从我选择的种子中获得的数据中的值。20如果它在您的数据集中,这将很好用。事实上,如果你有多个,它会起作用。
i, j = np.where(df.values == 55)
list(zip(df.index[i], df.columns[j]))
[(1, 'C')]
Run Code Online (Sandbox Code Playgroud)