遍历数据框的行以填充python中的列

时间:2020-01-17 22:36:29

标签: python dataframe

我有以下数据框(称为data_coh):

      roi     mag       phase     coherence
0      1   0.699883  0.0555903       NaN
1      2   0.640482     0.1053       NaN
2      3   0.477865    1.14926       NaN
3      4   0.128119    2.28403       NaN
4      5   0.563046    2.53091       NaN
5      6    0.58869    0.94647       NaN
6      7   0.428383    1.13915       NaN
7      8   0.164036    1.95959       NaN
8      9    0.27912    3.07456       NaN
9     10   0.244237    2.78111       NaN
10    11   0.696592    2.61011       NaN
11    12   0.237346    3.01836       NaN

对于每一行,我想按以下方式计算其相干值(请注意, 使用虚数单位j):

import math
import cmath

for roin, val in enumerate(data_coh):
    data_coh.loc[roin,'coherence'] = mag*math.cos(phase) + mag*math.sin(phase)*j

首先,它无法执行计算(这是基于幅度和相位来计算复数)。 J是一个复数单位(来自cmath)。 但是此外,即使忽略了j,也不会对行进行分配 正确地。为什么会这样,如何纠正呢?

1 个答案:

答案 0 :(得分:1)

只需熊猫和numpy,就无需迭代或导入mathcmath

import pandas as pd
import numpy as np

df['coherence'] = df['mag'] * (np.cos(df['phase']) + 1j*df['phase'])

# Result
df

    roi       mag    phase           coherence
0     1  0.699883  0.05559  0.698802+0.038907j
1     2  0.640482  0.10530  0.636934+0.067443j
2     3  0.477865  1.14926  0.195525+0.549191j
3     4  0.128119  2.28403 -0.083826+0.292628j
4     5  0.563046  2.53091 -0.461279+1.425019j
5     6  0.588690  0.94647  0.344119+0.557177j
6     7  0.428383  1.13915  0.179221+0.487992j
7     8  0.164036  1.95959 -0.062182+0.321443j
8     9  0.279120  3.07456 -0.278493+0.858171j
9    10  0.244237  2.78111  -0.228539+0.67925j
10   11  0.696592  2.61011 -0.600502+1.818182j
11   12  0.237346  3.01836 -0.235546+0.716396j