Python 模仿R语言的一些功能 filter/query rep/np.repeat
  X5zJxoD00Cah 2023年11月02日 40 0

筛选 管道函数 如同r语言中的tidyverse.filter

df.query(" 列名 判断 ")
series.to_frame.query(" 列名 判断 ")

生成元素重复的列表 如同r语言中的rep和rep_len函数

# R语言中 rep(x, times = 1, length.out = NA, each = 1)

# times 所有元素循环 Python实现
[1,2,3]*2

# 或者
# tile函数功能:对整个数组进行复制拼接 numpy.tile(a, reps)
arr_before = np.array([1,2,3])
np.tile(arr_before, 2)


# each 每个元素重复 Python实现
# repeat函数功能:对数组中的元素进行连续重复复制 numpy.repeat(a, repeats, axis=None)
np.repeat([1,2,], 2)

# 或者
list_before = [1, 2, 3]
list_after = [val for val in list_before for i in range(3)]

https://www.qiniu.com/qfans/qnso-46166933

https://blog.csdn.net/sinat_26811377/article/details/98469964

https://blog.csdn.net/zyl1042635242/article/details/43052403

列表降维 sum()函数的妙用

newlist = sum(oldlist,[])

https://segmentfault.com/a/1190000018903731

Pandas 以表格样式显示 DataFrame

https://www.delftstack.com/zh/howto/python-pandas/pandas-display-dataframe-in-a-table-style/

np.tile(A, reps)

If reps has length d, the result will have dimension of max(d, A.ndim).

If A.ndim < dA is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.

If A.ndim > dreps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.

repeat

Repeat elements of an array.

broadcast_to

Broadcast an array to a new shape

https://numpy.org/doc/stable/reference/generated/numpy.tile.html

# 如果A的维数为1
# if A.ndim == 1

# 如果reps的长度为0 
# reps.ndim <  A.ndim
import numpy as np
np.tile( 0 , '') # array(0)
np.tile([0], '') # array([0])
np.tile([0], ()) # array([0])

# 如果reps的长度为1 
# reps.ndim == A.ndim
# 此时开始 A = 0 或 A = [0] 输出结果一致
np.tile([0], 0) # array([], dtype=int32)
np.tile([0], 1) # array([0])
np.tile([0], 2) # array([0, 0])

# 如果reps的长度为2
# reps.ndim >  A.ndim
# 可以发现3条规律:
# 1
# 由于np.array([0,0])和np.array((0,0))的结果都是array([0, 0])
# 所以reps的形式可以是[]也可以是() 效果一致
# 2
# np.tile([0], [0,0]) # array([], shape=(0, 0), dtype=int32)
# np.tile([0], [0,1]) # array([], shape=(0, 1), dtype=int32)
# 可见reps中只要有一个元素为0 返回结果为[] 但shape会随着reps改变
# 3
# []与() 维数为0
# 单个元素(包含空字符串'')与[单个元素]与(单个元素) 维数为1
np.tile([0], [1,2])
# array([[0, 0]])
np.tile([0], [2,1])
# array([[0],
#        [0]])
np.tile([0], [2,2]) 
# array([[0, 0],
#        [0, 0]])

# 如果A的维数... reps的长度...足与不足...

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  X5zJxoD00Cah   2023年12月11日   15   0   0 知乎Python迭代器
  X5zJxoD00Cah   2023年12月12日   17   0   0 Python.net
X5zJxoD00Cah