使用索引遍历列

2024-04-24 05:41:34 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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:]:

有没有更好的办法?你知道吗


Tags: columnsinpandasdfforindexcol1mike
2条回答

我找到了下面的解决方案,但不确定这是否是正确的方法,我是新来的熊猫。你知道吗

import pandas as pd 

# initialize list of lists 
data = [['tom', 10], ['nick', 15], ['juli', 14]] 

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Age']) 
for ind, column in enumerate(df.columns):
  print(ind, column)

我相信您需要按列名循环,对于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])

通过^{}转置,您的解决方案是可行的,但在我看来有点过于复杂:

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))

相关问题 更多 >