20个pandas使用技巧

246 阅读3分钟

大家好,我是小寒。

原文连接

今天来分享 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 中一列的元素个数 ,请使用groupbycount
  • 如果要获取由 2 列或更多列组成的组的大小,请改用groupbysize
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、重命名聚合列

11、归一化值计数

12、df.transform()

13、填写空值

14、计算缺失值

15:过滤 DataFrame 中的列

16、自动转换数据类型

17、读取 HTML 表格

18、最大和最小

19、创建排名列

20、DataFrame 中的颜色值