簡體   English   中英

遍歷具有索引的列

[英]Iterating over columns with index

我如何遍歷 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:]:

有沒有更好的方法來做到這一點?

我相信您需要按列名循環,對於 select 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])

您的解決方案可以通過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))

我找到了以下解決方案,但不確定這是否是正確的方法,我是 pandas 的新手。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM