Cloud_Hari
Cloud_Hari

Reputation: 49

How to extract text from specific rows based on column in pandas?

i have below csv file reading as df in pands

table       entity_name  node_name  src_name      table_col_name    look_up_indicator   type       keys
gw_policy   account       ns0       fullname      insured_name        N                 attribute   NA
gw_policy   polocy        ns1       agent_name    agent               N                 attribute   NA
gw_policy   account       ns2       phone_num     agent_phone         N                 attribute   NA

i reading the csv in to pandas and extracting the specific column value

Here in the case i extracting only 'agent' rows from 'table_col_name'

data = pd.read_csv(file_path)
policy=data.loc[data['table_col_name']=='agent']
print(policy)

So here in the case, it will print all the rows fields of policy

#Out put
gw_policy   polocy        ns1       agent_name    agent               N                 attribute   NA

Now i want to extracts only below rows

'ns1' 
'agent_name'

so how it is possible with Pandas?

Thanks

Upvotes: 1

Views: 241

Answers (2)

Bob
Bob

Reputation: 1070

Change

policy = data.loc[data['table_col_name']=='agent']

to

policy = data.loc[data['table_col_name']=='agent', ['node_name', 'src_name']]

The pandas documentation explains how you can index your dataframes: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#selection-by-label

Upvotes: 1

jezrael
jezrael

Reputation: 863031

You can add list of columns names for DataFrame.loc with boolean indexing:

policy=data.loc[data['table_col_name']=='agent', ['node_name', 'src_name']]
print(policy)

Upvotes: 1

Related Questions