'I am using pandas to check user input in multiple columns, i want output as entire row which matches input
below is my code:
for r in cols:
full_row_of_matched = cols[cols.isin([input_ip]).any(axis=1)]
exact_column = list(cols.columns[cols.eq(input_ip).any(0)])
res = full_row_of_matched.iloc[:, 1]
Below is the DF
eth0 eth1 eth2 server_group vars
10.1.0.1 172.10.1.3 172.10.11.3 A xyz
10.1.0.2 172.10.1.3 172.10.11.9 B abc
10.1.0.7 172.10.1.9 172.10.1.3 V qwe
in the above Df you can see ip 172.10.1.3 has duplicates, so if i provide input as 172.10.1.3 i need below output
IP provided 172.10.1.3 has been assigned to host xyz and mapped to interface eth1
IP provided 172.10.1.3 has been assigned to host abc and mapped to interface eth1
IP provided 172.10.1.3 has been assigned to host qwe and mapped to interface eth2
Solution 1:[1]
fetching matching rows (option1)
inp = '172.10.1.3'
(df
.melt(id_vars=['server_group', 'vars'], value_name='IP', var_name='interface')
.loc[lambda d: d['IP'].eq(inp)]
)
output:
server_group vars interface IP
3 A xyz eth1 172.10.1.3
4 B abc eth1 172.10.1.3
8 V qwe eth2 172.10.1.3
fetching matching rows (option2)
inp = '172.10.1.3'
df[df.eq(inp).any(1)]
or, to limit to the "eth" columns:
inp = '172.10.1.3'
df[df.filter(like='eth').eq(inp).any(1)]
output:
eth0 eth1 eth2. server_group. vars
0 10.1.0.1. 172.10.1.3 172.10.11.3. A xyz
older answer
Your question is unclear, but assuming you have inp as input, you could use:
inp = '172.10.1.3'
cols = list(df.columns[df.eq(inp).any(0)])
cols
# ['eth1']
If you want all combinations of matching row/col indices:
inp = '172.10.1.3'
import numpy as np
rows, cols = np.where(df.eq(inp))
indices = list(zip(df.index[rows], df.columns[cols]))
output: [(0, 'eth1')]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
