Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧中基于列的数据切片_Python_Pandas - Fatal编程技术网

Python 数据帧中基于列的数据切片

Python 数据帧中基于列的数据切片,python,pandas,Python,Pandas,我有这样一个数据帧: Month Day Year TmaxF 4 1 1912 56.00 4 2 1912 56.00 4 3 1912 74.00 1 1 1913 38 1 2 1913 28 1 3 1913 21 1 1 1914 30.00 1 2 1914 31.00 1 3 19

我有这样一个数据帧:

Month   Day Year    TmaxF
 4       1  1912    56.00
 4       2  1912    56.00
 4       3  1912    74.00
 1       1  1913    38
 1       2  1913    28
 1       3  1913    21
 1       1  1914    30.00
 1       2  1914    31.00
 1       3  1914    20.00
我只想选择1913年和1914年的数据
.isin
不是我想要的,因为这是一个简化的数据集

我更希望看到的是:

df.loc['1913':'1914'] 
但当我将
Year
设置为索引并运行此代码时,它会返回错误:

TypeError: cannot do slice indexing on <class 'pandas.core.index.Int64Index'> with these indexers [1913] of <type 'str'>

将年份设置为索引后,使用

这里我使用字符串作为索引:

df.index
#Index([u'1912', u'1912', u'1912', u'1913', u'1913', u'1913', u'1914', u'1914',
#   u'1914'],
#  dtype='object', name=u'Year')
看起来您的
Year
列原来是整数,所以您的索引可能是整数

df.index
#Int64Index([1912, 1912, 1912, 1913, 1913, 1913, 1914, 1914, 1914], dtype='int64', name=u'Year')

如果是这样,那么将切片器范围设置为整数:
df.loc[slice(19131914),:]
首先,请注意数据是数字(int64),而不是字符串。从您试图查询数据的方式来看,我相信您遵循了以日期作为索引的指南(在这种情况下,您可以按日期或部分日期进行切片)

撇开这一点不谈,重要的是要记住,
df.loc
用于根据索引进行切片(它不会出现在您发送的表中)

虽然您可以将年份设置为索引,但按照您的意愿对数据进行切片的更优雅的方法是使用:

df.index
#Index([u'1912', u'1912', u'1912', u'1913', u'1913', u'1913', u'1914', u'1914',
#   u'1914'],
#  dtype='object', name=u'Year')
df.index
#Int64Index([1912, 1912, 1912, 1913, 1913, 1913, 1914, 1914, 1914], dtype='int64', name=u'Year')
df[(df.Year >= 1913) && (df.Year <= 1914)]
df.index = df.Year
df.loc[1913:1914]