Pandas 与 NumPy 结合使用
Pandas 基于 NumPy 构建,两者紧密集成。理解它们的交互可以更高效地进行数据处理和科学计算。
相互转换
DataFrame/Series 与 NumPy 互转
实例
import pandas as pd
import numpy as np
# DataFrame 转 NumPy 数组
df = pd.DataFrame({
"A": [1, 2, 3],
"B": [4, 5, 6]
})
arr = df.to_numpy()
print("DataFrame 转数组:")
print(arr)
print(f"类型: {type(arr)}")
print()
# Series 转数组
s = pd.Series([1, 2, 3])
arr = s.values # 或 s.to_numpy()
print("Series 转数组:")
print(arr)
print()
# NumPy 转 DataFrame
arr = np.array([[1, 2], [3, 4], [5, 6]])
df = pd.DataFrame(arr, columns=["A", "B"])
print("数组转 DataFrame:")
print(df)
import numpy as np
# DataFrame 转 NumPy 数组
df = pd.DataFrame({
"A": [1, 2, 3],
"B": [4, 5, 6]
})
arr = df.to_numpy()
print("DataFrame 转数组:")
print(arr)
print(f"类型: {type(arr)}")
print()
# Series 转数组
s = pd.Series([1, 2, 3])
arr = s.values # 或 s.to_numpy()
print("Series 转数组:")
print(arr)
print()
# NumPy 转 DataFrame
arr = np.array([[1, 2], [3, 4], [5, 6]])
df = pd.DataFrame(arr, columns=["A", "B"])
print("数组转 DataFrame:")
print(df)
NumPy 函数在 Pandas 中使用
实例
import pandas as pd
import numpy as np
s = pd.Series([1, 2, 3, 4, 5])
# 使用 NumPy 函数
print("绝对值:", np.abs(s))
print("平方根:", np.sqrt(s))
print("指数:", np.exp(s))
print("对数:", np.log(s))
print()
# 条件筛选
print("大于3的值:")
print(s[s > 3])
import numpy as np
s = pd.Series([1, 2, 3, 4, 5])
# 使用 NumPy 函数
print("绝对值:", np.abs(s))
print("平方根:", np.sqrt(s))
print("指数:", np.exp(s))
print("对数:", np.log(s))
print()
# 条件筛选
print("大于3的值:")
print(s[s > 3])
向量化运算
实例
import pandas as pd
import numpy as np
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
# 向量化运算
print("A + B:", (df["A"] + df["B"]).tolist())
print("A * B:", (df["A"] * df["B"]).tolist())
print("A > B:", (df["A"] > df["B"]).tolist())
print()
# 使用 apply 进行逐元素计算
result = df.apply(lambda x: np.multiply(x, 2))
print("每个元素 * 2:")
print(result)
import numpy as np
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
# 向量化运算
print("A + B:", (df["A"] + df["B"]).tolist())
print("A * B:", (df["A"] * df["B"]).tolist())
print("A > B:", (df["A"] > df["B"]).tolist())
print()
# 使用 apply 进行逐元素计算
result = df.apply(lambda x: np.multiply(x, 2))
print("每个元素 * 2:")
print(result)
数值计算技巧
实例
import pandas as pd
import numpy as np
df = pd.DataFrame({
"A": [1, 2, 3, 4, 5],
"B": [10, 20, 30, 40, 50]
})
# 计算 A 相对于 B 的百分比变化
df["变化率"] = np.divide(df["A"], df["B"], where=df["B"] != 0) * 100
print("百分比变化:")
print(df)
print()
# 使用 np.where 进行条件赋值
df["标签"] = np.where(df["A"] > 3, "大", "小")
print("条件标签:")
print(df)
import numpy as np
df = pd.DataFrame({
"A": [1, 2, 3, 4, 5],
"B": [10, 20, 30, 40, 50]
})
# 计算 A 相对于 B 的百分比变化
df["变化率"] = np.divide(df["A"], df["B"], where=df["B"] != 0) * 100
print("百分比变化:")
print(df)
print()
# 使用 np.where 进行条件赋值
df["标签"] = np.where(df["A"] > 3, "大", "小")
print("条件标签:")
print(df)
统计计算
实例
import pandas as pd
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# NumPy 统计函数
print(f"均值: {np.mean(s):.2f}")
print(f"标准差: {np.std(s):.2f}")
print(f"最大值: {np.max(s)}")
print(f"最小值: {np.min(s)}")
print()
# 中位数
print(f"中位数: {np.median(s)}")
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# NumPy 统计函数
print(f"均值: {np.mean(s):.2f}")
print(f"标准差: {np.std(s):.2f}")
print(f"最大值: {np.max(s)}")
print(f"最小值: {np.min(s)}")
print()
# 中位数
print(f"中位数: {np.median(s)}")
Pandas 和 NumPy 的深度集成使得复杂的数据处理变得简单高效。
