首页 > 解决方案 > 如何迭代具有相同索引的系列

问题描述

我希望遍历包含相同索引组的系列。数据如下:

0      -0.969886
0      -0.941016
0      -0.913815
0      -0.888142
0      -0.863872
      ...   
3423   -0.841284
3423   -0.840156
3423   -0.839032
3423   -0.837911
3423   -0.836792
Length: 13828, dtype: object

以下是for循环代码:

ln_gamma_i = []
ln_gamma_j = []
for i in range(len(tau_21)):
    ln_gamma_i.append(x2**2 * (tau_21[i] * (g_21[i]/(x1 + x2 * g_21[i]))**2 + tau_12[i] * 
                      g_12[i]/(x2 + x1 * g_12[i])**2))
    ln_gamma_j.append(x1**2 * (tau_12[i] * (g_12[i]/(x2 + x1 * g_12[i]))**2 + tau_21[i] * 
                      g_21[i]/(x1 + x2 * g_21[i])**2))

tau_21 的长度与 tau_12、g_21 和 g_12 相等。我不能简单地计算没有 for 循环的方程,因为 x1 和 x2 的大小 = 5。所以每次迭代有 5 个输出。如何迭代行而不是索引。我意识到有 iterrows 或 iteritems 但据我了解,这些似乎对 1 个系列有帮助,这里我有 4 个不同的系列。

标签: pythonpandasdataframefor-loop

解决方案


您可以使用 zip 创建两个迭代器和循环的元组:

a=[1,2,3]
b=[9,8,7]
c=zip(a,b)
for i,n in c:
    print(str(i) +" " + str(n))

... 
1 9
2 8
3 7

https://docs.python.org/3.8/library/functions.html#zip


推荐阅读