df.loc方法,根据行、列的标签值查询,.loc既能查询,又能覆盖写入,强烈推荐。
pandas使用df.loc查询数据的方法:
- 使用单个label值查询数据。
- 使用值列表批量查询。
- 使用数值区间进行范围查询。
- 使用条件表达式查询。
- 调用函数查询。
首先读取一份数据:
import pandas as pd
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
df=pd.read_csv(r'data\sh600000.csv',encoding='gbk')
print(df.head(20)) #先调用前20条数据看看是否正常

然后设置索引为日期,方便以后按日期进行数据筛选:
df.set_index('交易日期',inplace=True) #设置索引为日期,方便按日期筛选
df.index
print(df.head(20))

1、使用单个label值查询数据,(假如:我想查询2017年3月15日的最高价是多少?)代码如下:
import pandas as pd
pd.set_option('display.unicode.ambiguous_as_wide', True) #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True) #无法对齐主要是因为列标题是中文
df=pd.read_csv(r'data\sh600000.csv',encoding='gbk')
df.set_index('交易日期',inplace=True) #设置索引为日期,方便按日期筛选
df.index
height=df.loc['2017-3-15','最高价']
print(height)
得到的结果就是16.28

又例如我想查询2019年3月18日的“最低价”和“收盘价”,代码如下:
import pandas as pd
pd.set_option('display.unicode.ambiguous_as_wide', True) #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True) #无法对齐主要是因为列标题是中文
df=pd.read_csv(r'data\sh600000.csv',encoding='gbk')
df.set_index('交易日期',inplace=True) #设置索引为日期,方便按日期筛选
df.index
result=df.loc['2019-3-18',['最低价','收盘价']]
print(result)

2、使用值列表批量查询,(假如我想查询2001年3月20、21、22日,这3天的最高价是多少?),代码如下:
result=df.loc[['2001-3-20','2001-3-21','2001-3-22'],'最高价']
print(result)

又或者我想查询 2001年3月20、21、22日,这3天的最高价和最低价是多少 ?代码可以这样写:(行和列都传入一个list)
result=df.loc[['2001-3-20','2001-3-21','2001-3-22'],['最高价','最低价']]
print(result)

3、使用数值区间进行范围查询,( 假如我想查询2001年3月20日至2001年3月30日,这10天区间的最高价是多少? 【它既可以在行传入:代表区间,也可以在列传入:代表区间】)
result=df.loc['2001-3-20':'2001-3-30','最高价']
print(result)

result=df.loc['2001-3-20','最高价':'前收盘价']
print(result)

result=df.loc['2001-3-20':'2001-3-30','最高价':'前收盘价']
print(result)

4、使用条件表达式查询,(假如我需要查询2008年全年,最高价大于50并且小于60的数据)
year=df.loc['2008-1-2':'2008-12-31',]
result=year[(df['最高价']>50) & (df['最高价']<60)]
print(result)

注意:多条件查询时(组合条件用 & 符号合并,每个条件判断都得带括号)