[英]How can I easily iterate at the same time through rows and columns?
我有以下df
如果單元格中有數值,則返回索引值和列名:
A B C
04/04/18 Nan Nan Nan
05/04/19 Nan 4 Nan
06/04/20 Nan Nan 5
隨着輸出:
["B-05/04/19","C-06/04/20"]
有沒有什么簡單的方法可以在不需要嵌套循環的情況下同時遍歷行和列?
如果對列和索引值進行排序,則使用帶有dropna
stack
並在列表理解中最后加入MulitIndex
:
s = df.stack().dropna()
idx = ['{}-{}'.format(b, a) for a, b in s.index]
#python 3.6+
#idx = [f'{b}-{a}' for a, b in s.index]
print (idx)
['B-05/04/19', 'C-06/04/20']
或者獲取非 NaN 值的索引,獲取索引值並連接在一起:
x, y = np.where(df.notnull())
idx = df.columns[y] + '-' + df.index[x]
print (idx)
Index(['B-05/04/19', 'C-06/04/20'], dtype='object')
類似於 jezrael 的解決方案,但使用numpy.argwhere
:
>>> idx = np.argwhere(df.notna().values)
>>> ['{}-{}'.format(df.columns[j], df.index[i]) for i, j in idx]
['B-05/04/19', 'C-06/04/20']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.