「numpy」ndarray 逻辑运算,通用判断,三元运算,统计量计算

numpy ndarray 运算


更多内容请关注本人【numpy】专栏


【目录】

  • 逻辑运算
  • 通用判断函数
  • 三元运算符 np.where()
  • 统计计算
一、逻辑运算
  • 所有逻辑运算符,比如:>, <, >=, ==
x = np.random.randint(0, 100, (2, 3))
print(x)
print(x > 50)
x[x < 30] = 1
print(x)

# 返回结果
[[69 62 23]
 [21 89 25]]

[[ True  True False]
 [False  True False]]

[[69 62  1]
 [ 1 89  1]]
二、通用判断函数
  • np.all(exp) 全部满足才行
  • np.any(exp) 有一个满足就行
x = np.array([[69, 62, 23], [21, 89, 25]])

np.all(x > 60)	# False

np.any(x > 80)	# True
三、三元运算符
  • np.where(exp),返回一个结果对象
    • 与C/C++中的三元运算符语法、功能一致
x = np.array([[69, 62, 23], [21, 89, 25]])

y = np.where(x > 60, 1, 0)	# 大于60的赋值为1,否则为0

print(y)

# 返回结果
[[1 1 0]
 [0 1 0]]

  • np.logical_and 和 np.local_or
    • 复合型逻辑运算
x = np.array([[69, 62, 23], [21, 89, 25]])

y1 = np.where(np.logical_and(x > 60, x < 90), 1, 0)

y2 = np.where(np.logical_or(x > 90, x < 60), 1, 0)

print(y1)
# 返回结果
[[1 1 0]
 [0 1 0]]

print(y2)
# 返回结果
[[0 0 1]
 [1 0 1]]
四、统计计算
  • min(a, axis)
    • 计算最小值,axis表示指定行或者列,默认不指定
  • max(a, axis])
    • 计算最大值,axis表示指定行或者列,默认不指定
  • median(a, axis)
    • 计算中位数,axis表示指定行或者列,默认不指定
  • mean(a, axis, dtype)
    • 计算平均值,axis表示指定行或者列,默认不指定
  • std(a, axis, dtype)
    • 计算标准差,axis表示指定行或者列,默认不指定
  • var(a, axis, dtype)
    • 计算方差,axis表示指定行或者列,默认不指定
x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(f"数组中的最小值:{np.min(x)}")
print(f"数组中的最大值:{np.max(x)}")
print(f"数组中的中位数:{np.median(x)}")
print(f"数组中的平均值:{np.mean(x)}")
print(f"数组中的标准差:{np.std(x):.2f}")
print(f"数组中的方差:{np.var(x)}")

# 返回结果
数组中的最小值:1
数组中的最大值:10
数组中的中位数:5.5
数组中的平均值:5.5
数组中的标准差:2.87
数组中的方差:8.25

  • np.argmax(a, axis=)
  • np.argmin(a, axis=)
    • 两个函数表示的是最大值和最小值对应的数组下标
x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(f"数组最大值对应的下标:{np.argmax(x)}")
print(f"数组最小值对应的下标:{np.argmin(x)}")

# 返回结果
数组最大值对应的下标:9
数组最小值对应的下标:0
### 数据分析与数据挖掘的区别 数据分析通常是指对已有的数据进行处理、统计和可视化,以提取有用的信息并支持决策。数据挖掘则是一种更深层次的技术,它通过算法和模型从大量数据中发现隐藏的模式和规律[^1]。 ### NumPy广播机制示例 NumPy广播机制允许形状不同的数组进行算术运算,只要它们的维度满足一定的条件。例如: ```python import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) result = a + b print(result) ``` 上述代码展示了如何将一个一维数组与二维数组相加,结果是将`b`的每个元素加到`a`的对应列上[^2]。 ### Pandas中merge与concat区别 `merge()`函数主要用于基于键值合并两个DataFrame,类似于数据库中的连接操作,支持内连接、外连接、左连接和右连接。而`concat()`函数则是直接按行或列拼接多个DataFrame,不涉及键值匹配[^3]。 ```python import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1'], 'B': ['B0', 'B1']}) df2 = pd.DataFrame({'A': ['A2', 'A3'], 'B': ['B2', 'B3']}) merged_df = pd.merge(df1, df2, how='outer') concatenated_df = pd.concat([df1, df2], axis=0) ``` ### 生成词云步骤 生成词云需要使用`wordcloud`库,其基本步骤包括加载文本数据、创建词云对象并生成图像,最后保存或显示图像[^1]。 ```python from wordcloud import WordCloud import matplotlib.pyplot as plt text = "重复的词语越多越明显" wordcloud = WordCloud().generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show() ``` ### 箱线图特征 箱线图(Boxplot)用于显示数据分布的五数概括:最小值、第一四分位数(Q1)、中位数(Q2)、第三四分位数(Q3)和最大值。此外,它还能标识出离群点[^3]。 ```python import matplotlib.pyplot as plt data = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9] plt.boxplot(data) plt.show() ``` ### np.where用法 `np.where()`函数可以根据条件返回不同值的数组,类似于三元表达式[^2]。 ```python import numpy as np arr = np.array([1, 2, 3, 4, 5]) result = np.where(arr > 3, 'High', 'Low') print(result) ``` ### Matplotlib figure与axes关系 在Matplotlib中,`figure`代表整个画布,而`axes`是画布上的坐标系区域。一个`figure`可以包含多个`axes`,每个`axes`独立绘制图形[^3]。 ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) plt.show() ``` ### 随机矩阵列最大值替换 可以通过`np.argmax()`找到每列的最大值索引,并用特定值替换[^2]。 ```python import numpy as np matrix = np.random.randint(0, 100, (5, 5)) max_indices = np.argmax(matrix, axis=0) for col in range(matrix.shape[1]): matrix[max_indices[col], col] = -1 print(matrix) ``` ### DataFrame平均工资计算 假设有一个包含工资信息的DataFrame,可以使用`mean()`方法计算平均工资[^1]。 ```python import pandas as pd data = {'salary': [3000, 4000, 5000]} df = pd.DataFrame(data) average_salary = df['salary'].mean() print(average_salary) ``` ### DataFrame按customer_id左连接合并 使用`pd.merge()`函数可以实现基于`customer_id`的左连接。 ```python import pandas as pd df1 = pd.DataFrame({'customer_id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie']}) df2 = pd.DataFrame({'customer_id': [2, 3, 4], 'age': [25, 30, 35]}) merged_df = pd.merge(df1, df2, on='customer_id', how='left') print(merged_df) ``` ### 年龄离散化统计 可以使用`pd.cut()`函数将年龄分段并统计每段的数量[^1]。 ```python import pandas as pd ages = [22, 25, 27, 30, 35, 40, 45, 50] bins = [20, 30, 40, 50, 60] groups = pd.cut(ages, bins) print(groups.value_counts()) ``` ### 绘制正弦曲线并保存 使用`matplotlib`绘制正弦曲线并保存为文件[^3]。 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.savefig('sine_wave.png') plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值