ppa*_*ler 5 python numpy pandas
pandas.DataFrame我尝试按照离散时间信号的公式计算信号能量。我尝试使用applyand applymap,也尝试使用reduce,如下所示:How do I columnwise reduce a pandas dataframe? 。但我尝试的所有结果都是对每个元素进行操作,而不是对整个列进行操作。
这不是一个信号处理特定的问题,它只是一个如何将“汇总”(我不知道这个的正确术语)函数应用于列的示例。
我的解决方法是获取原始numpy.array数据并进行计算。但我很确定有一种熊猫式的方法可以做到这一点(而且肯定是一种更笨拙的方法)。
import pandas as pd
import numpy as np
d = np.array([[2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[0, -1, 2, -3, 4, -5, 6, -7, 8, -9],
[0, 1, -2, 3, -4, 5, -6, 7, -8, 9]]).transpose()
df = pd.DataFrame(d)
energies = []
# a same as d
a = df.as_matrix()
assert(np.array_equal(a, d))
for column in range(a.shape[1]):
energies.append(sum(a[:,column] ** 2))
print(energies) # [40, 285, 285]
Run Code Online (Sandbox Code Playgroud)
提前致谢!
您可以对数据帧输出执行以下操作 -
\n\n(df**2).sum(axis=0) # Or (df**2).sum(0)\nRun Code Online (Sandbox Code Playgroud)\n\n为了提高性能,我们可以使用从数据帧中提取的数组 -
\n\n(df.values**2).sum(axis=0) # Or (df.values**2).sum(0)\nRun Code Online (Sandbox Code Playgroud)\n\n为了进一步提升性能,有np.einsum-
a = df.values\nout = np.einsum('ij,ij->j',a,a)\nRun Code Online (Sandbox Code Playgroud)\n\n运行时测试 -
\n\nIn [31]: df = pd.DataFrame(np.random.randint(0,9,(1000,30)))\n\nIn [32]: %timeit (df**2).sum(0)\n1000 loops, best of 3: 518 \xc2\xb5s per loop\n\nIn [33]: %timeit (df.values**2).sum(0)\n10000 loops, best of 3: 40.2 \xc2\xb5s per loop\n\nIn [34]: def einsum_based(a):\n ...: a = df.values\n ...: return np.einsum('ij,ij->j',a,a)\n ...: \n\nIn [35]: %timeit einsum_based(a)\n10000 loops, best of 3: 32.2 \xc2\xb5s per loop\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1378 次 |
| 最近记录: |