2016-11-08 75 views
-1

我在索引某些列时遇到问题。当我尝试这样的索引上的Python:.loc在Pandas-Python中建立索引

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

我收到以下错误: 类型错误:不能做切片与这些索引[1980]的

索引,如果我尝试这样的:

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

我得到以下错误:

KeyError异常: '1980年'

dtype是float64。我希望能够调用列1980 - 1987年的列标签,并删除那些列,但不调用索引列号,但是标签。

谢谢

+0

不确定具体问题。但快速修复将是'df1.select(lambda x:1980 <= x <1987)' – shanmuga

+0

您能提供一个独立的示例来演示问题吗? – BrenBarn

回答

0

切片适用于任何类型的列。看下面的例子。也许,你必须检查你的数据和/或给我们提供一个例子。

# 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 
+0

你好,谢谢你的回答我的数据表看起来像这样:2064 2065 2066 2067 2068 2069 2070 0楠楠楠楠楠楠的NaN 1 NaN的楠楠楠楠楠楠 2楠楠楠楠楠楠的NaN – user1682697

+0

当我运行print(df1.loc [:,2060:2062])我得到以下消息:TypeError:无法对使用这些索引器[2060] user1682697

+0

进行索引该dtypes是:2060 float64 2061 float64 2062 float64 2063 float64 2064 float64 2065 float64 2066 float64 2067 float64 2068 float64 2069 float64 2070 float64 – user1682697