简体   繁体   中英

.loc indexing in Pandas-Python

I am having and issue with indexing of some columns. when i try indexing like that on python:

list(df1.loc[:,1980:1987])

I get the following error: TypeError: cannot do slice indexing on with these indexers [1980] of

If i try it like that:

list(df1.loc[:,'1980':'1987'])

I get the following error:

KeyError: '1980'

The dtype is float64. I want to be able to call the column label which ia year for columns 1980-1987 and drop those but without calling the index column number but the label.

Thank you

Slicing works on columns whatever their type. See the examples below. Maybe, you have to check your data and / or provide us an example.

# Test data
df = pd.DataFrame({'1980': ['A', 'B'], 
                   '1981': ['A', 'B'], 
                   '1982': ['A', 'B']})

# With string
print(df.columns.dtype)
print(df.loc[:,'1980':'1981'])

# object
#   1980 1981
# 0    A    A
# 1    B    B

# With integer
df.columns = df.columns.astype('int')
print(df.columns.dtype)
print(df.loc[:,1980:1981])

# int64
#   1980 1981
# 0    A    A
# 1    B    B

# With float
df.columns = df.columns.astype('float')
print(df.columns.dtype)
print(df.loc[:,1980:1981])

# float64
#   1980.0 1981.0
# 0      A      A
# 1      B      B

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