学会这 29 个 函数,你就是 Pandas 专家

admin 2022年11月9日13:13:58评论26 views字数 10125阅读33分45秒阅读模式

点击上方“萝卜大杂烩”,选择“星标公众号

超级无敌干货,第一时间送达!!!


学会这 29 个 函数,你就是 Pandas 专家



Pandas 无疑是 Python 处理表格数据最好的库之一,但是很多新手无从下手,这里总结出最常用的 29 个函数,先点赞收藏,留下印象,后面使用的时候打开此文 CTRL + F 搜索函数名称,检索其用法即可。

1、读取 csv 文件 df.read_csv

csv 通常是读取 Pandas DataFrame 的最流行的文件格式,你可以使用 pd.read_csv() 方法创建 Pandas DataFrame,类似的函数还有 read_excel,用法如下:

file = "file.csv"

df = pd.read_csv(file)
print(df)
####### out put ##########
   col1  col2 col3
0     1     2    A
1     3     4    B

2、写入 csv 文件 df.to_csv

将 DataFrame 导出到 csv,类似的函数是 df.to_excel,用法如下:

df.to_csv("file.csv", sep = "|", index = False)

查看 file.csv

!cat file.csv
col1|col2|col3
1|2|A
3|4|B

3、数据帧 pd.DataFrame

用来创建 Pandas 的 DataFrame:

data = [[12"A"], 
        [34"B"]]

df = pd.DataFrame(data, 
                  columns = ["col1""col2""col3"])
print(df)

####### out put ##########
   col1  col2 col3
0     1     2    A
1     3     4    B

借助这个构造函数,我们还可以把字典转换为 DataFrame:

data = {'col1': [12], 
        'col2': [34], 
        'col3': ["A""B"]}

df = pd.DataFrame(data=data)
print(df)
####### out put ##########
   col1  col2 col3
   col1  col2 col3
0     1     3    A
1     2     4    B

4、 获取数据帧的形状 df.shape

df.shape 属性可以获取 DataFrame 的形状,也就是几行几列这样的数据:

print(df)
print("Shape:", df.shape)
####### out put ##########
   col1  col2 col3
   col1  col2 col3
0     1     3    A
1     2     4    B

Shape: (23)

5、查看前 n 行 df.head(n)

数据帧(DataFrame) 会有很多行,通常我们只对查看 DataFrame 的前 n 行感兴趣,这时可以使用 df.head(n) 方法打印前 n 行:

print(df.head(5))
####### out put ##########
   col1  col2 col3
0     1     2    A
1     3     4    B
2     5     6    C
3     7     8    D
4     9    10    E

6、打印列的类型 df.dtypes

Pandas 为 DataFrame 中的每一列分配适当的数据类型。使用 dtypes 参数打印所有列的数据类型:

df.dtypes

####### out put ##########
col1     int64
col2     int64
col3    object
dtype: object

7、修改列的类型 astype

如果要更改列的数据类型,可以使用 astype() 方法,如下所示:

df["col1"] = df["col1"].astype(np.int8)
print(df.dtypes)
####### out put ##########
col1      int8
col2     int64
col3    object
dtype: object

8-9、打印有关 DataFrame 的描述性信息

这里有两个函数,第一个 df.info():

df.info()
####### out put ##########
<class 'pandas.core.frame.DataFrame'>
RangeIndex:
 10 entries, 0 to 9
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   col1    10 non-null     int8  
 1   col2    10 non-null     int64 
 2   col3    10 non-null     object
dtypes: int64(1), int8(1), object(1)
memory usage: 298.0+ bytes

第二个是 df.describe()。

如果要打印每个数值列的平均值、标准偏差、最大值等标准统计信息,就可以这样:

print(df.describe())
####### out put ##########
        col1   col2
count  10.00  10.00
mean   10.00  11.00
std     6.06   6.06
min     1.00   2.00
25%     5.50   6.50
50%    10.00  11.00
75%    14.50  15.50
max    19.00  20.00

10、 填充 NaN 值 df.fillna

假如有这样的 DataFrame:

df = pd.DataFrame([[12"A"], [np.nan, 4"B"]], 
                  columns = ["col1""col2""col3"])
print(df)
####### out put ##########
   col1  col2 col3
0   1.0     2    A
1   NaN     4    B

里面有 NaN,如果要填充它,可以这样:

df.fillna(0, inplace = True)
print(df)
######## out put ##########
   col1  col2 col3
0   1.0     2    A
1   0.0     4    B

11、数据帧的关联 df.merge

如果你想用一个连接键合并两个 DataFrame,使用 pd.merge() 方法:

merge 之前:

df1 = ...
df2 = ...

print(df1)
print(df2)
######## out put ##########
   col1  col2 col3
0     1     2    A
1     3     4    A
2     5     6    B
  col3 col4
0    A    X
1    B    Y

使用 df.merge 后,可以生成新的数据帧

pd.merge(df1, df2, on = "col3")
######## out put ##########
  col1  col2 col3 col4
0     1     2    A    X
1     3     4    A    X
2     5     6    B    Y

12、数据帧排序 df.sort_values

排序是 DataFrame 非常典型的操作,我们可以使用 df.sort_values() 方法对 DataFrame 进行排序:

f = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"B"]], 
                  columns = ["col1""col2""col3"])

print(df.sort_values("col1"))
######## out put ##########
   col1  col2 col3
0     1     2    A
2     3    10    B
1     5     8    B

13、数据帧分组 df.groupby

要对 DataFrame 进行分组并执行聚合,使用 Pandas 中的 groupby() 方法,如下所示:

df = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"B"]], 
                  columns = ["col1""col2""col3"])

df.groupby("col3").agg({"col1":sum, "col2":max})
######## out put ##########
      col1  col2
col3            
A        1     2
B        8    10

14、重命名列 df.rename

如果要重命名列标题,请使用 df.rename() 方法,如下所示:

f = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"B"]], 
                  columns = ["col1""col2""col3"])

df.rename(columns = {"col1":"col_A"})

######## out put ##########

   col_A  col2 col3
0     1     2    A
1     5     8    B
2     3    10    B

15、删除列 df.drop

如果要删除数据帧中的某一列,可以这样:

df = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"B"]], 
                  columns = ["col1""col2""col3"])

print(df.drop(columns = ["col1"]))

######## out put ##########

   col2 col3
0     2    A
1     8    B
2    10    B

16、增加列

方法一:使用赋值运算符添加新列

df = pd.DataFrame([[12], [34]], 
                  columns = ["col1""col2"])

df["col3"] = df["col1"] + df["col2"]
print(df)

######## out put ##########

   col1  col2  col3
0     1     2     3
1     3     4     7

方法二:df.assign()

df = pd.DataFrame([[12], [34]], 
                  columns = ["col1""col2"])

df = df.assign(col3 = df["col1"] + df["col2"])

print(df)

######## out put ##########

   col1  col2  col3
0     1     2     3
1     3     4     7

17、数据帧过滤-布尔型过滤

如果该行上的条件评估为 True,则选择该行:

df = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"B"]], 
                  columns = ["col1""col2""col3"])

print(df[df["col2"] > 5])

######## out put ##########

   col1  col2 col3
1     5     8    B
2     3    10    B

18、数据帧过滤-之获取某一列

df["col1"## or df.col1

######## out put ##########

0    1
1    5
2    3
Name: col1, dtype: int64

19、数据帧过滤-按标签选择 df.loc

在基于标签的选择中,要求的每个标签都必须在 DataFrame 的索引中。整数也是有效的标签,但它们指的是标签而不是索引位置。

假如有如下 DataFrame:

df = pd.DataFrame([[65,  10], 
                   [58,  6], 
                   [3104]], 
                  columns = ["Maths""Science""English"],
                  index = ["John""Mark""Peter"])

print(df)

######## out put ##########

       Maths  Science  English
John       6        5       10
Mark       5        8        6
Peter      3       10        4

我们使用 df.loc 方法进行基于标签的选择:

df.loc["John"]

######## out put ##########

Maths       6
Science     5
English    10
Name: John, dtype: int64
df.loc["Mark", ["Maths""English"]]

######## out put ##########

Maths      5
English    6
Name: Mark, dtype: int64

但是在df.loc[]中,不允许使用索引来过滤 DataFrame,如下图:

20、数据帧过滤-按索引选择 df.iloc

以 19 里面的数据帧为例,使用 df.iloc 可以用索引:

df.iloc[0]

######## out put ##########

Maths       6
Science     5
English    10
Name: John, dtype: int64

21、数据帧中对某一列去重

df = pd.DataFrame([[12,  "A"], 
                   [58,  "B"], 
                   [310"A"]], 
                  columns = ["col1""col2""col3"])

df["col3"].unique()

######## out put ##########

array(['A''B'], dtype=object)

22、数据帧中获取某一列去重后的个数

df["col3"].nunique()

######## out put ##########

2

23、将函数应用于 DataFrame df.apply

非常实用:

def add_cols(row):
    return row.col1 + row.col2

df = pd.DataFrame([[12], 
                   [58], 
                   [39]], 
                  columns = ["col1""col2"])
                  
df["col3"] = df.apply(add_cols, axis=1)
print(df)

######## out put ##########

   col1  col2  col3
0     1     2     3
1     5     8    13
2     3     9    12

还可以将方法应用于单个列,如下所示:

def square_col(num):
    return num**2

df = pd.DataFrame([[12], 
                   [58], 
                   [39]], 
                  columns = ["col1""col2"])
                  
df["col3"] = df.col1.apply(square_col)
print(df)

######## out put ##########

   col1  col2  col3
0     1     2     1
1     5     8    25
2     3     9     9

24、标记重复行 df.duplicated

你可以使用 df.duplicated() 方法标记所有重复的行

df = pd.DataFrame([[1"A"], 
                   [2"B"], 
                   [1"A"]], 
                  columns = ["col1""col2"])
                  
df.duplicated(keep=False)

######## out put ##########

0     True
1    False
2     True
dtype: bool

25、删除重复行 df.drop_duplicates

可以使用 df.drop_duplicates() 方法删除重复的行,如下所示:

df = pd.DataFrame([[1"A"], 
                   [2"B"], 
                   [1"A"]], 
                  columns = ["col1""col2"])
                  
print(df.drop_duplicates())

######## out put ##########

col1 col2
0     1    A
1     2    B

26、寻找值的分布 value_counts

要查找列中每个唯一值的频率,请使用 df.value_counts() 方法:

df = pd.DataFrame([[1"A"], 
                   [2"B"], 
                   [1"A"]], 
                  columns = ["col1""col2"])
                  
print(df.value_counts("col2"))

######## out put ##########

col2
A    2
B    1
dtype: int64

27、 重置 DataFrame 的索引 df.reset_index

要重置 DataFrame 的索引,请使用 df.reset_index() 方法:

df = pd.DataFrame([[65,  10], 
                   [58,  6], 
                   [3104]], 
                  columns = ["col1""col2""col3"],
                  index = [231])

print(df.reset_index())

######## out put ##########

   index  col1  col2  col3
0      2     6     5    10
1      3     5     8     6
2      1     3    10     4

要删除旧索引,请将 drop=True 作为参数传递给上述方法:

df.reset_index(drop=True)

######## out put ##########

   col1  col2  col3
0     6     5    10
1     5     8     6
2     3    10     4

28、查找交叉表 df.crosstab

要返回跨两列的每个值组合的频率,请使用 pd.crosstab() 方法:

df = pd.DataFrame([["A""X"], 
                   ["B""Y"], 
                   ["C""X"],
                   ["A""X"]], 
                  columns = ["col1""col2"])

print(pd.crosstab(df.col1, df.col2))

######## out put ##########

col2  X  Y
col1      
A     2  0
B     0  1
C     1  0

29、透视数据帧

数据透视表是 Excel 中常用的数据分析工具。与上面讨论的交叉表类似,Pandas 中的数据透视表提供了一种交叉制表数据的方法。

假如 DataFrame 如下:

df = ...

print(df)
    Name  Subject  Marks
0   John    Maths      6
1   Mark    Maths      5
2  Peter    Maths      3
3   John  Science      5
4   Mark  Science      8
5  Peter  Science     10
6   John  English     10
7   Mark  English      6
8  Peter  English      4

使用 pd.pivot_table() 方法,可以将列条目转换为列标题:

pd.pivot_table(df, 
               index = ["Name"],
               columns=["Subject"], 
               values='Marks',
               fill_value=0)

######## out put ##########

Subject  English  Maths  Science
Name                            
John          10      6        5
Mark           6      5        8
Peter          4      3       10

最后的话

恭喜你看完了 Pandas 中最常用的 29 种方法,后面在使用 Pandas 时,你可能会在 90% 的时间里使用这些方法,点赞、收藏、关注,后续使用 Pandas 不迷路。

学会这 29 个 函数,你就是 Pandas 专家

人生苦短,我用python
神秘礼包获取方式
点击下方公众号回复:1024

学会这 29 个 函数,你就是 Pandas 专家

推荐阅读  点击标题可跳转

原文始发于微信公众号(萝卜大杂烩):学会这 29 个 函数,你就是 Pandas 专家

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年11月9日13:13:58
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   学会这 29 个 函数,你就是 Pandas 专家https://cn-sec.com/archives/1393507.html

发表评论

匿名网友 填写信息