暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

20 个 pandas 常用技巧

程序员学长 2022-12-26
368

大家好,我是小寒。

今天来分享 20 个常用的 pandas 使用技巧。如果觉得不错,点赞、转发安排起来。

1、以 Markdown 格式输出 DataFrame

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': [5, 6, 7, 8]})

# You can control the printing of the index column by using the flag index.
print(df.to_markdown(index=True))

| | 一个 | 乙 | 
|---:|----:|----:| 
| 0 | 1 | 5 | 
| 1 | 2 | 6 | 
| 2 | 3 | 7 | 
| 3 | 4 | 8 |

2、将行分组到列表中

通常用 groupby
 获取同一组中行的统计信息,例如计数、均值、中位数等。如果要将行分组到列表中,请使用“ lambda x: list(x)
”。

import pandas as pd

df = pd.DataFrame(
    {
        "col1": [1, 2, 3, 4, 3],
        "col2": ["a""a""b""b""c"],
        "col3": ["d""e""f""g""h"],
    }
)

# Group by col2
df.groupby(["col2"]).agg(
    {
        "col1""mean",           # get mean
        "col3": lambda x: list(x) # get list
    }
)

3、DataFrame.explode()

使用 DataFrame
 时,如果要将字符串转换为列表,然后将列表中的元素拆分为多行,请使用 str.split()
 和 explode()
 方法。

import pandas as pd

df = pd.DataFrame({"a": ["1,2""4,5"],
                   "b": [11, 13]})

# Turn strings into lists
df.a = df.a.str.split(",")
df

df.explode("a", ignore_index=False)

4、DataFrame.copy()

你是否曾经尝试过使用 “ = ” 来复制一个 DataFrame ?你不会得到一份副本,改变新的DataFrame
也会改变原来的DataFrame

制作副本的更好方法是使用 df.copy()
。现在,更改副本不会影响原始DataFrame

import pandas as pd
df = pd.DataFrame({"col1": [1, 2, 3],
                   "col2": [4, 5, 6]})

df2 = df 
#改变 df2 
df2["col1"] = [7, 8, 9]
# df 也跟着改变
df 

df = pd.DataFrame({"col1": [1, 2, 3],
                   "col2": [4, 5, 6]})

# 使用 copy 创建一个副本
df3 = df.copy() 
# 改变 df3
df3["col1"] = [7, 8, 9]
# df 不会改变
df 

5、Groupby().count 与 Groupby().size

  • 如果要获取 Pandas DataFrame
     中一列的元素个数 ,请使用groupby
     和 count

  • 如果要获取由 2 列或更多列组成的组的大小,请改用groupby
     和  size
import pandas as pd
df = pd.DataFrame(
    {
        "col1": ["a""b""b""c""c""d"],
        "col2": ["S""S""M""L""L""L"]
    }
)

# get the count of elements in one column
df.groupby(["col1"]).count()

df.groupby(["col1""col2"]).size()

6、相关性

如果要计算两个 DataFrame 的行或列之间的相关性,请使用.corrwith()
.

import pandas as pd

df1 = pd.DataFrame({
    "a": [1, 2, 3, 4],
    "b": [2, 3, 4, 6]
})

df2 = pd.DataFrame({
    "a": [1, 2, 3, 3],
    "b": [2, 2, 5, 4]
})

df1.corrwith(df2)

7、交叉表

交叉表允许你分析多个变量之间的关系。要将 PandasDataFrame
转换为交叉表,请使用pandas.crosstab()

import pandas as pd

network = [
    ("Ben""Smith"),
    ("Ben""Patrick"),
    ("Warren""Jone"),
    ("Warren""Smith"),
    ("Smith""Patrick"),
]

# Create a dataframe of the network
friends1 = pd.DataFrame(
    network, columns=["person1""person2"]
)

# Create the order of the columns
friends2 = pd.DataFrame(
    network, columns=["person2""person1"]
)


# Create a symmetric dataframe
friends = pd.concat([friends1, friends2])

print(friends)

# Create a cross tabulation
df_cross=pd.crosstab(friends.person1, friends.person2)

print(df_cross)

8、DataFrame.query()

可以使用 df.query()
 过滤行。
import pandas as pd

df = pd.DataFrame({
    "fruit": ["apple""orange""grape""grape"],
    "price": [4, 5, 6, 7]
})

# Filter using brackets
df[(df.price > 4) & (df.fruit == "grape")]

使用 df.query() 来进行简化处理。

df.query("price > 4 & fruit == 'grape'")

9、pandas.melt()

  • 如果要将 DataFrame 从宽格式转为长格式,请使用pandas.melt()
  • 例如,你可以使用pandas.melt()
    将多列(“Aldi”、“Walmart”、“Costco”)转换为一列(“store”)的值。
import pandas as pd

df = pd.DataFrame({
    "fruit": ["apple""orange"],
    "Aldi": [4, 5],
    "Walmart": [6, 7],
    "Costco": [1, 2]
})

df

# Turn Aldi, Walmart, Costco into values of "store"
df.melt(id_vars=["fruit"],
        value_vars=["Aldi""Walmart""Costco"],
        var_name='store')

10、重命名聚合列

默认情况下,聚合列会返回该列的名称。如果要为聚合分配新名称,请使用name = (column, agg_method)
.

import pandas as pd

df = pd.DataFrame({"size": ["S""S""M""L"],
                   "price": [44, 29.99, 10, 19]})

df.groupby('size').agg({'price''mean'})

# 分配一个新的名字
df.groupby('size').agg(
    mean_price=('price''mean')
)

11、归一化值计数

  • 如果要获取列中值的计数,请使用value_counts
    .
  • 但是,如果要获取列中某个值的百分比,可以在 value_counts 方法中设置 normalize=True 。

import pandas as pd

size = pd.Series(["S""S""M""L""S""XL""S""M",])

# 获得每个值的计数
size.value_counts()

# 获得每个值的占比
size.value_counts(normalize=True)

12、df.transform()

pandas  DataFrame
 要根据类别的出现次数进行过滤 ,你可以尝试使用df.groupby
df.count
。但是由于 count 方法返回的 Series 比原来的要短,所以DataFrame
过滤的时候会报错。
所以我们使用transform
方法。此方法将返回与原始序列具有相同长度的 Series 。现在你可以过滤而不会遇到任何错误。
import pandas as pd

df = pd.DataFrame({
    "type": ["A""A""O""B""O""A"],
    "value": [5, 3, 2, 1, 7, 3]
})

# Using count will throw an error because the
# Series returned is shorter than the original
# DataFrame

# df.loc[df.groupby("type")["type"].count() > 1]
df.loc[df.groupby("type")["type"].transform("size") > 1]

13、填写空值

  • 如果要使用 另一个 DataFrame 的相同位置的非空值填充一个 DataFrame 的空值,请使用pandas.DataFrame.combine_first
    .
import pandas as pd

store1 = pd.DataFrame({
    "orange": [None, 5, 9],
    "apple": [4, None, 12]
})

store2 = pd.DataFrame({
    "orange": [31, 52, 91],
    "apple": [11, 71, 21]
})

# Fill null values of the store1 with values at the same
# locations from store2
print(store1.combine_first(store2))

14、计算缺失值

默认情况下,pandas.value_counts()
忽略缺失值。通过dropna=False
以使其计算缺失值。
import pandas as pd
size = pd.Series(["S""S", None, "M""L""S", None, "XL""S""M",])

# 获取每一个值的计数,不包括缺失值
size.value_counts()


S      4
M      2
NaN    2
XL     1
L      1
dtype: int64

# 包括缺失值进行计数
size.value_counts(dropna=False)

S     4
M     2
XL    1
L     1
dtype: int64

15:过滤 DataFrame 中的列

如果要根据名称中的字符过滤 pandas DataFrame 的列,请使用 DataFrame.filter。
如果你创建虚拟变量并且想要根据前缀选择列,这会很方便。
import pandas as pd
df = pd.DataFrame({'Temp': ['Hot''Cold''Warm''Cold'],
                   'Degree': [35, 3, 15, 2]})
print(df)

   Temp  Degree
0   Hot      35
1  Cold       3
2  Warm      15
3  Cold       2

df = pd.get_dummies(df, columns=['Temp'])
print(df)

   Degree  Temp_Cold  Temp_Hot  Temp_Warm
0      35          0         1          0
1       3          1         0          0
2      15          0         0          1
3       2          1         0          0

print(df.filter(like='Temp', axis=1))

   Temp_Cold  Temp_Hot  Temp_Warm
0          0         1          0
1          1         0          0
2          0         0          1
3          1         0          0

16、自动转换数据类型

如果你不知道 DataFrame 中列的 dtypes,你可以使用 convert_dtypes() 来快速将列转换为可能的最佳类型。

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
        "b": pd.Series(["x""y""z"], dtype=np.dtype("O")),
        "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
        "d": pd.Series(["h""i", np.nan], dtype=np.dtype("O")),
        "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
        "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    }
)

df.dtypes

a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

new_df = df.convert_dtypes()
new_df.dtypes

a      Int32
b     string
c    boolean
d     string
e      Int64
f    Float64
dtype: object

17、读取 HTML 表格

import pandas as pd

table = pd.read_html(
    "https://en.wikipedia.org/wiki/Minnesota"
    match="Election results from statewide races"
)

print(table[0].head())

table = pd.read_html(
    "https://en.wikipedia.org/wiki/Minnesota"
    match="Average daily"
)

print(table[0].head())

18、最大和最小

使用 .nlargest() 和 .nsmallest() 对列进行排序,而不是使用 DataFrame.sort_values()`.

import pandas as pd
df = pd.read_csv('data/imdbratings.csv',
                 usecols=['star_rating''title''genre''duration'])

print(df.head())

    star_rating                     title   genre  duration
0          9.3  The Shawshank Redemption   Crime       142
1          9.2             The Godfather   Crime       175
2          9.1    The Godfather: Part II   Crime       200
3          9.0           The Dark Knight  Action       152
4          8.9              Pulp Fiction   Crime       154

print(df.nlargest(5, "duration"))

     star_rating                              title      genre  duration
476          7.8                             Hamlet      Drama       242
157          8.2                 Gone with the Wind      Drama       238
78           8.4        Once Upon a Time in America      Crime       229
142          8.3  Lagaan: Once Upon a Time in India  Adventure       224
445          7.9               The Ten Commandments  Adventure       220

print(df.nsmallest(5, "duration"))

     star_rating                        title    genre  duration
389          8.0                       Freaks    Drama        64
338          8.0          Battleship Potemkin  History        66
258          8.1  The Cabinet of Dr. Caligari    Crime        67
88           8.4                      The Kid   Comedy        68
293          8.1                    Duck Soup   Comedy        68

19、创建排名列

Pandas 中 DataFrame.rank() 方法返回传递的 Series 的每个相应索引的排名。
在以下示例中,创建了一个新的排名列,该列根据学生的分数对学生进行排名。
import pandas as pd
df = pd.DataFrame({'Students': ['John''Smith''Patrick''Bob''Jose'],
                   'Marks': [80, 56, 95, 75, 45]})
print(df)
df["Rank"] = df["Marks"].rank(ascending=False)
print(df)

  Students  Marks
0     John     80
1    Smith     56
2  Patrick     95
3      Bob     75
4     Jose     45
  Students  Marks  Rank
0     John     80   2.0
1    Smith     56   4.0
2  Patrick     95   1.0
3      Bob     75   3.0
4     Jose     45   5.0

20、DataFrame 中的颜色值

颜色样式增加了最终用户的可读性。Pandas 具有 style 属性,我们可以将不同的样式应用于 DataFrame。

import pandas as pd

df = pd.DataFrame({'Students': ['John''Smith''Patrick''Bob''Jose'],
                   'Physics': [80, 56, 95, 75, 45], 
                   'Mathematics': [90, 85, 55, 65, 75]})
df.set_index('Students', inplace=True)
df

def pass_condition(val):
    color = 'blue' if val > 70 else 'red'
    return f"background-color: {color}"

df.style.applymap(pass_condition)


最后



今天的分享就到这里。如果觉得不错,点赞,转发安排起来吧。
接下来我们会分享更多的 「深度学习案例以及python相关的技术」,欢迎大家关注。
最后,最近新建了一个 python 学习交流群,会经常分享 「python相关学习资料,也可以问问题,非常棒的一个群」

「进群方式:加我微信,备注 “python”」



往期回顾


Fashion-MNIST 服装图片分类-Pytorch实现

python 探索性数据分析(EDA)案例分享

深度学习案例分享 | 房价预测 - PyTorch 实现

万字长文 |  面试高频算法题之动态规划系列

面试高频算法题之回溯算法(全文六千字)  

    




如果对本文有疑问可以加作者微信直接交流。进技术交流群的可以拉你进群。

文章转载自程序员学长,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论