disukumo
disukumo

Reputation: 341

Extract data based the condition using python

I have the following dataframe (df):

Col_A Col_B Col_C
123 A 1Q
124 B L1
125 B QW
126 A E2

If the user selects a particular column and the value the entire row should be saved as a new dataframe. For example, if the user selects Col_A 123 the output should be the following:

Col_A Col_B Col_C
123 A 1Q

If the user selects Col_B: B and Col_A: 125 then the output should e the following:

Col_A Col_B Col_C
125 B QW

If the user selects Col_B: B then the output shoud be the following:

Col_A Col_B Col_C
124 B L1
125 B QW

How do I do that?

What I tried so far?


import pandas as pd
import numpy as np
df= pd.read_csv('Table.csv')
print('Enter the value as 99 if the Col_A or Col_B is not known')
Col_A_value= (input(str("Enter tag of your interest separated by ',': ")).split(","))
Col_B_value= (input(str("Enter iris_image_id of your interest separated by ',': ")).split(","))
input_table = []
for i,j in itertools.product(Col_A_value, Col_B_value):
    if len(i) > 0 and len(j)==0:
        input_table.append(df[df['Col_A'] == i])
    elif i != '99' and len(j)> 0:
        input_table.append(df[df['Col_A'] == i]) 

The above script does not extract a particular data if Col_A and Col_B are specified. If I specify Col_A = 124 and Col_B = B it results everything in col_B.

Desired output:

Col_A Col_B Col_C
124 B L1

Upvotes: 0

Views: 1877

Answers (2)

yhn
yhn

Reputation: 131

you can try this :

import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [3, 4]}
df = pd.DataFrame(data=d)
print(df)
print(df[(df['col1']==1) & (df['col2']==3)])

Result : enter image description here

----------- OR --------

Try to use the pandas function where (link to pandas.where tuto), It is better to use function than loops

Upvotes: 1

Fareed Khan
Fareed Khan

Reputation: 2933

# Importing Libraries
import pandas as pd

# Importing dataframe
df = pd.read_csv('mydata.csv')


# Col A Value input as int
first_input = int(input('Enter Col A Value'))

# Col B value input as string
second_input = str(input('Enter Col B Value'))

# checking both column values with == sign 
df[(df['Col_A'] == first_input) & (df['Col_B']== second_input)]

Upvotes: 0

Related Questions