简体   繁体   中英

how to extract whole row using .loc or .iloc function if index is non-integer value

Here is the output of my code but now I want to extract the values of Check_In and Check_Out in variables so that I can perform own these values any suggestions on how to extract the values?

ID    Name        Check_In           Check_Out           
1     Zainab      7 am       5 pm
2   Abdullah      8 am       5 pm
3     Hassan      9 am       6 pm
4    Javeria     11 am       9 pm
5     Tayyab      7 am       5 pm
6     Fatima     11 am       9 pm

This is my code below:

import pandas as pd
import numpy as np
df = pd.read_csv("Book1.csv")
c = df.set_index('ID')
print(c)
f = int(input('Give ID number:' ))
t = (pd.DataFrame((c.loc[f])))
print(t)

This is the prompt:

Give ID number:2
>> 2

Name       Abdullah
Check_In        8am
Check_Out       5pm

You can use pandas.DataFrame.values after user input the choice of ID . Since .values returns a NumPy array, I had to use slice indexing. ( Scenario if user enters 2 as input )

check_in = t.loc['Check_In'].values[0] 
check_out = t.loc['Check_Out'].values[0] 
print(check_in)
print(check_out) 

Output:

8:00 AM
5:00 PM

This will set your index to "Name" as well as select an index that is a string instead of a int

df.set_index('Name', inplace = True)
df.loc[['Zainab']].squeeze()

You can remove the .squeeze() if you simply want to have a df of the results.

IUUC, you can use Series.loc

c = df.set_index('ID')
f = 2
t = c.loc[f]
check_in = t.loc['Check_In']
check_out = t.loc['Check_Out']

# without `t`
check_in = c.loc[f, 'Check_In']
print(check_in)
8 am

print(check_out)
5pm

Or you can use

check_ins = df.loc[df['ID'].eq(f), 'Check_In'].tolist()
print(check_ins)

['8 am']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM