首页 > 解决方案 > 遍历具有索引的列

问题描述

我如何在 pandas 中迭代具有索引的列,对于我们可以使用的行for i, j in df.iterrows():,它将给出索引和行。

列有类似的东西吗?

spice smice skice bike dike mike 
    1     23     35    34   34   56 
    135   34     23    21   56   34
    231   12     67    21   62   75

我正在尝试使用嵌套的 for 循环,如下所示:

for index, col1 in  df.columns:
  for col2 in df.columns[index:]:

有没有更好的方法来做到这一点?

标签: pythonpandas

解决方案


我相信您需要按列名循环并按列名Series选择:

for col_name in df.columns:
    print (col_name)
    print (df[col_name])

替代解决方案,缺点是可读性更差:

for col_name in df:
    print (col_name)
    print (df[col_name])

您的解决方案可以使用 transpose by DataFrame.T,但在我看来有点过于复杂:

for col_name, s in df.T.iterrows():
    print (col_name)
    print (s)

编辑:

for col_name in df.columns:
    print (col_name)
    print (df[col_name])
    print (df.columns.get_loc(col_name))

推荐阅读