pandas DataFrame 用法–查看和选择数据

目录

1. 使用 .head() 查看 DataFrame 头部数据

2. 使用 .tail() 查看 DataFrame 尾部数据

3. 使用 .describe() 查看 DataFrame 统计数据

4. 使用 .T 查看 DataFrame 转置数据

5. at 函数:通过行名和列名来取值

6.iat 函数:通过行号和列号来取值

7. loc函数主要通过 行标签 索引行数据

8. iloc函数主要通过行号、索引行数据

9.ix——通过行标签或者行号索引行数据

10. 使用布尔索引查看符合要求的数据

11. 使用 sample() 查看随机数据

12. 使用 isin() 查看数据是否符合条件

13. 使用 .shape 查看查看行数和列数

14. 使用 .info() 查看索引、数据类型和内存信息

在使用各种api之前,先创建测试使用数据:

代码:

import numpy as np
import pandas as pd
dict_data={"a":list("abcdef"),"b":list("defghi"),"c":list("ghijkl")}
df=pd.DataFrame.from_dict(dict_data)
df

运行结果:

Out[1]:

abc0adg1beh2cfi3dgj4ehk5fil

  1. 使用 .head() 查看 DataFrame 头部数据

.head([n]) 用法如下,如果 n 为空,则默认为 5

In [12]: df.head(0)
Out[12]:
In [13]: df.head(1)
Out[13]:
abc0adgIn [16]: df.head(3)
Out[16]:
abc0adg1beh2cfi

  1. 使用 .tail() 查看 DataFrame 尾部数据

.tail([n]),如果 n 为空,则默认为 5

In [18]: df.tail(0)
Out[18]:
In [19]: df.tail(1)
Out[19]:
abc5filIn [20]: df.tail(3)
Out[20]:
abc3dgj4ehk5fil

  1. 使用 .describe() 查看 DataFrame 统计数据

.describe 语法如下

Help on function describe in module pandas.core.generic:

describe(self: 'FrameOrSeries', percentiles=None, include=None, exclude=None, datetime_is_numeric=False) -> 'FrameOrSeries'
    Generate descriptive statistics.

    Descriptive statistics include those that summarize the central
    tendency, dispersion and shape of a
    dataset's distribution, excluding  values.

    Analyzes both numeric and object series, as well
    as  column sets of mixed data types. The output
    will vary depending on what is provided. Refer to the notes
    below for more detail.

    Parameters
    ----------
    percentiles : list-like of numbers, optional
        The percentiles to include in the output. All should
        fall between 0 and 1. The default is
        [.25, .5, .75], which returns the 25th, 50th, and
        75th percentiles.

    include : 'all', list-like of dtypes or None (default), optional
        A white list of data types to include in the result. Ignored
        for . Here are the options:

        - 'all' : All columns of the input will be included in the output.

        - A list-like of dtypes : Limits the results to the
          provided data types.

          To limit the result to numeric types submit
          .number. To limit it instead to object columns submit
          the .object data type. Strings
          can also be used in the style of
          select_dtypes (e.g. .describe(include=['O'])). To
          select pandas categorical columns, use 'category'
        - None (default) : The result will include all numeric columns.

    exclude : list-like of dtypes or None (default), optional,
        A black list of data types to omit from the result. Ignored
        for . Here are the options:

        - A list-like of dtypes : Excludes the provided data types
          from the result. To exclude numeric types submit
          .number. To exclude object columns submit the data
          type .object. Strings can also be used in the style of
          select_dtypes (e.g. .describe(include=['O'])). To
          exclude pandas categorical columns, use 'category'
        - None (default) : The result will exclude nothing.

    datetime_is_numeric : bool, default False
        Whether to treat datetime dtypes as numeric. This affects statistics
        calculated for the column. For DataFrame input, this also
        controls whether datetime columns are included by default.

.describe() 默认是对数值类进行统计

In [21]: df.describe()
Out[21]:
abccount666unique666topaejfreq111

也可以通过 include=object 来获得对其他的统计

例如当前数据

pandas DataFrame 用法--查看和选择数据

获得两种不同的结果

pandas DataFrame 用法--查看和选择数据
  1. 使用 .T 查看 DataFrame 转置数据
In [24]: df.T

Out[24]:
012345aabcdefbdefghicghijkl

  1. at 函数 :通过行名和列名来取值

先创建数据吧

import pandas as pd
import pdb
#pdb.set_trace()
dict_data={"X":list("abcdef"),"Y":list("defghi"),"Z":list("ghijkl")}
df=pd.DataFrame.from_dict(dict_data)
df.index=["A","B","C","D","E","F"]
df

生成如下 DataFrame

pandas DataFrame 用法--查看和选择数据

用法太简单了,直接把 at 和 iat 都运行上。

A 行 X 列数据,必须两个数据都输入,否则报错
print(df.at["A","X"])
第二 行 第二 列数据,序号从0开始
print(df.iat[2,2])

运行结果

a
i
  1. iat 函数 :通过行号和列号来取值

请参考7,请注意 at 是按照 行名列名来定位某个元素,而 iat 是按照 行号列号来定位某个元素。

  1. loc函数主要通过 行标签 索引行数据

当前 df 如下

pandas DataFrame 用法--查看和选择数据

loc 非常简单,直接看完代码就明白了

指定行名和列名的方式,和at的用法相同
print(df.loc["A","X"],"\n","*"*20)

可以完整切片,这是 at 做不到的
print(df.loc[:,"X"],"\n","*"*20)

可以从某一行开始切片
print(df.loc["B":,"X"],"\n","*"*20)

可以只切某一列
print(df.loc["B",:],"\n","*"*20)

和指定上一条代码效果是一样的
print(df.loc["B"],"\n","*"*20)

运行结果

a
 ********************
A    a
B    b
C    c
D    d
E    e
F    f
Name: X, dtype: object
 ********************
B    b
C    c
D    d
E    e
F    f
Name: X, dtype: object
 ********************
X    b
Y    e
Z    h
Name: B, dtype: object
 ********************
X    b
Y    e
Z    h
Name: B, dtype: object
 ********************

8. iloc函数主要通过行号、索引行数据

当前 df 如下

pandas DataFrame 用法--查看和选择数据

和 iloc 用法非常类似,直接看代码吧,不再多说

指定行号和列号的方式,和 loc 的用法相同
print(df.iloc[0,0],"\n","*"*20)

可以完整切片
print(df.iloc[:,0],"\n","*"*20)

可以从某一行开始切片
print(df.iloc[1:,0],"\n","*"*20)

可以只切某一列
print(df.iloc[1,:],"\n","*"*20)

和指定上一条代码效果是一样的
print(df.iloc[1],"\n","*"*20)

运行结果

a
 ********************
A    a
B    b
C    c
D    d
E    e
F    f
Name: X, dtype: object
 ********************
B    b
C    c
D    d
E    e
F    f
Name: X, dtype: object
 ********************
X    b
Y    e
Z    h
Name: B, dtype: object
 ********************
X    b
Y    e
Z    h
Name: B, dtype: object
 ********************

9. ix——通过行标签或者行号索引行数据

ix 是基于loc和iloc 的混合,但是现在已经被弃用了。说实话我很喜欢这种弃用,确实它能做的事情,用上面的 loc 和 iloc 也能做到,就不再赘述。

10. 使用布尔索引查看符合要求的数据

当前 df 如下

pandas DataFrame 用法--查看和选择数据

使用 df[] 切片取出符合筛选条件的数据,& 是条件与,| 是条件或。

取一行数据,这行数据符合两个条件。
1)Y 列 字符的 ASCI 码大于字符 g,
2)Z 列 字符的 ASCI 码小于字符 x,
print(df[(df["Y"].str.lower()>"g")&(df["Z"].str.lower()

运行结果还是挺理想的

X  Y  Z
E  e  h  k
F  f  i  l
 ********************
   X  Y  Z
A  a  d  g

11. 使用 sample() 查看随机数据

语法:DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)

参数说明:

n:这是一个可选参数, 由整数值组成, 并定义生成的随机行数。
frac:它也是一个可选参数, 由浮点值组成, 并返回浮点值数据帧值的长度。 不能与参数n一起使用。*
replace:由布尔值组成,默认值是false。如果为true, 则返回带有替换的样本。
权重:它也是一个可选参数, 由类似于str或ndarray的参数组成。默认值”无”将导致相等的概率加权。
random_state:它也是一个可选参数, 由整数或numpy.random.RandomState组成。如果值为int, 则为随机数生成器或numpy RandomState对象设置种子。
axis:它也是由整数或字符串值组成的可选参数。 0或”行”和1或”列”。

这里只介绍最简单的用法。

print("*"*20)
print(df.sample())
print("*"*20)
print(df.sample())
print("*"*20)
print(df.sample())
print("*"*20)
print(df.sample())

运行结果每次都不一样

********************
   X  Y  Z
A  a  d  g
********************
   X  Y  Z
F  f  i  l
********************
   X  Y  Z
A  a  d  g
********************
   X  Y  Z
B  b  e  h

12. 使用 isin() 查看数据是否符合条件

语法:dataframe.isin(values),values 可以是dataframe,也可以是一列数据。

#可以整个 dataframe 进行比较
df2=df.copy()
print(id(df)) # 此处用 id ,是为了注明两个dataframe 内存已经不一样了
print(id(df2))
df["G"]=list("MKLHGF")
df2.isin(df)

运行结果

XYZATrueTrueTrueBTrueTrueTrueCTrueTrueTrueDTrueTrueTrueETrueTrueTrueFTrueTrueTrue

取一列进行比较

#取G列 进行值比较
df.G.isin(list("MKLHGF"))

运行结果

A    True
B    True
C    True
D    True
E    True
F    True
Name: G, dtype: bool

13. 使用 .shape 查看查看行数和列数

太简单了

In [23]: df.shape

Out[23]:

(6, 3)

14. 使用 .info() 查看索引、数据类型和内存信息

`
In [21]: df.info()

RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
# Column Non-Null Count Dtype

Original: https://blog.csdn.net/u010701274/article/details/121252117
Author: 江南野栀子
Title: pandas DataFrame 用法–查看和选择数据

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/752412/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球