Python学习笔记——pandas
官方文档:https://pandas.pydata.org/docs/reference/index.html
1.loc属性,通过标签或布尔数组访问一组行和列。pandas.DataFrame.loc
>>> df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], ... index=['cobra', 'viper', 'sidewinder'], ... columns=['max_speed', 'shield']) >>> df max_speed shield cobra 1 2 viper 4 5 sidewinder 7 8
获取单个label,返回是一个series
>>> df.loc['viper'] max_speed 4 shield 5 Name: viper, dtype: int64
获取List of labels。注意使用 [[]]
返回的是一个 DataFrame
>>> df.loc[['viper', 'sidewinder']] max_speed shield viper 4 5 sidewinder 7 8
通过行标签和列标签来获得具体值
>>> df.loc['cobra', 'shield'] 2
对行进行切片,对列进行单标签切片(取得部分行和部分列)
>>> df.loc['cobra':'viper', 'max_speed'] cobra 1 viper 4 Name: max_speed, dtype: int64
通过boolean值来选取部分行
>>> df.loc[[False, False, True]] max_speed shield sidewinder 7 8
条件筛选符合条件的行或者列
>>> df.loc[df['shield'] > 6] max_speed shield sidewinder 7 8
条件筛选后再指定某个列
>>> df.loc[df['shield'] > 6, ['max_speed']] max_speed sidewinder 7
多个条件
>>> df.loc[(df['max_speed'] > 1) & (df['shield'] < 8)] max_speed shield viper 4 5 >>> df.loc[(df['max_speed'] > 4) | (df['shield'] < 5)] max_speed shield cobra 1 2 sidewinder 7 8
本文只发表于博客园和tonglin0325的博客,作者:tonglin0325,转载请注明原文链接:https://www.cnblogs.com/tonglin0325/p/6054893.html