程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(4)

python pandas包数据定位([] & index & loc & iloc & where & query)

发布于2019-08-05 19:27     阅读(3405)     评论(0)     点赞(5)     收藏(0)


IO文件读写:IO文件读写

1. 基本方法

series[lable]
frame[colname]

2. 通过index

sa = pd.Series([1, 2, 3], index=list(‘abc’))

sa.b为 2

3. iloc & loc

iloc
df.iloc[0]: 第0行数据(series)
df.iloc[[0]]: 第0行数据(dataframe)
df.iloc[[0, 1]]: 第0、1行数据(dataframe)
df.iloc[:3]: 前三行数据(dataframe)
df.iloc[[True, False, True]]:第0、2行数据(dataframe)

df.iloc[0, 1]:坐标(0,1)的数据
df.iloc[[0, 2], [1, 3]]: 坐标(0,1)(0,3)(2,1)(2,3)数据组成的矩阵
df.iloc[:, lambda df: [0, 2]]:第0、2列数据

loc
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],index=[‘one’, ‘two’, ‘three’],columns=[‘a’, ‘b’])
df.loc[‘one’]:one行数据
df.loc[[‘one’, ‘two’]]:one、two行数据

多索引情况:

创建多索引dataframe:

tuples = [(‘cobra’, ‘mark i’), (‘cobra’, ‘mark ii’),(‘sidewinder’, ‘mark i’), ‘sidewinder’, ‘mark ii’), (‘viper’, ‘mark ii’), (‘viper’,‘mark iii’)]
index = pd.MultiIndex.from_tuples(tuples)
values = [[12, 2], [0, 4], [10, 20],[1, 4], [7, 1], [16, 36]]
df = pd.DataFrame(values, columns=[‘max_speed’, ‘shield’], index=index)
在这里插入图片描述

4. where() & mask()

DataFrame.where(self, cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False)

s.where(s > 0):大于0的数据
df.where(df < 0, -df) 等价于 df[df < 0]:将所有小于0的数据取反

mask()是where()的反函数

5. query()

df.query(’(a < b) & (b < c)’) 等价于 df[(df.a < df.b) & (df.b < df.c)]
df.query(‘a > 2’)
df.query(‘a not in b’) 等价于 df[~df.a.isin(df.b)]
df.query(‘a in b + c + d’)
df.query(‘c == [1, 2]’)

【reference】:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc



所属网站分类: 技术文章 > 博客

作者:没事就吃溜溜梅

链接:https://www.pythonheidong.com/blog/article/7023/7d9c0c44cdde5ad1e018/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)