简体   繁体   中英

Issues while using .loc with a Pandas dataframe

    raw=pd.read_csv('raw_6_12_8_30.csv')
    raw2=raw.loc[raw['spices'].isnull()==False]  # code for deleting 10 values #

    b=[]

    for i in range(len(raw2)):
        if raw2['Status'][i]==0:            # codes didn't run perfectly#
            print(i)

But when I use this code without line 2, it works fine.

    raw=pd.read_csv('raw_6_12_8_30.csv')
    b=[]

    for i in range(len(raw)):
        if raw['Status'][i]==0:            
            print(i)

I checked there is no errors in this raw2['Status] and raw['Status']

But whenever I use pandas.loc ,there is an error.

I bet that line 2 makes an error but I don't know why?

error images here enter image description here

key errors 11 # what is it #

there are 3 ways to get values from dataframe by indexing.

  1. loc gets rows (or columns) with particular labels from the index.

  2. iloc gets rows (or columns) at particular positions in the index (so it only takes integers).

  3. ix usually tries to behave like loc but falls back to behaving like iloc if a label is not present in the index.

if you want to take values by indexing you can use iloc. Like in the code below

raw=pd.read_csv('raw_6_12_8_30.csv')
b=[]

for i in range(len(raw)):
    if raw['Status'].iloc[i]==0:            
        print(i)

can you try with:

for i in range(0,len(raw)-1):

i guess key error 11 occur because of index range. the key 11 may be out of range.

Are you trying to drop all rows where spices is null ?

raw.dropna(subset="spices", inplace=True)

To print where the status is 0:

raw_subset = raw[raw["Status"]==0]
print(raw_subset)

# To get the specific indices
print(raw_subset.index)

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