Python input to select specific rows
I have a dataframe where I would like to utilize Input function to select a row or a group of rows.
Data
type stat country
aa1 y ca
bb2 n ny
cc3 y tx
Desired
Use Input("select type value: ")
type in: aa1, bb2
*selects appropriate rows
type stat country
aa1 y ca
bb2 n ny
Doing
out = Input("select type value: ")
df.loc[df['type'].isin([aa1, bb2])]
I am thinking that I can combine .loc along w input() Any suggestion is appreciated.
Because input is strings with ,
only use split
for list ['aa1','bb2']
with strip for remove traliling spaces, because type aa1,bb2
not aa1, bb2
like mentioned in question:
df[df['type'].isin([x.strip() for x in out.split(',')])]
Use query
:
out = input("select type value: ")
vals = [v.strip() for v in out.split(',')]
df1 = df.query('type.isin(@vals)')
print(df1)
Ouput
select type value: aa1,bb2
type stat country
0 aa1 y ca
1 bb2 n ny
Update
Is there a way to capture the remaining dataset? once selected (The subset that was not sliced)
Use a boolean mask:
out = input("select type value: ")
vals = [v.strip() for v in out.split(',')]
mask = df['type'].isin(vals)
df1 = df.loc[mask]
df2 = df.loc[~mask]
Output:
>>> df1
type stat country
0 aa1 y ca
1 bb2 n ny
>>> df2
type stat country
2 cc3 y tx