【问题标题】:How to iterate over a series with identical indices如何迭代具有相同索引的系列
【发布时间】:2021-08-07 15:12:43
【问题描述】:

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

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 个不同的系列。

【问题讨论】:

  • 要获取唯一索引列表,您可以使用idx = set(df['col'].tolist())。然后您可以使用df.where 遍历 idx 的元素以获取具有此值的所有元素。

标签: python pandas dataframe for-loop


【解决方案1】:

您可以使用 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

【讨论】:

  • 看来我只能在 print 中执行操作(例如 print(i+2) 等),但是,我不能附加结果(例如 empty_list.append(i+2 ) 返回 empty_list = [])。附加代码适用于您的代码,它们是列表,我拥有的数据是系列。
猜你喜欢
  • 2018-12-25
  • 2019-07-10
  • 1970-01-01
  • 2018-10-22
  • 2017-09-08
  • 2014-01-15
  • 2021-02-22
  • 2019-01-13
  • 2019-09-26
相关资源
最近更新 更多