[英]How can I easily iterate at the same time through rows and columns?
I have the following df
where if there is a numerical value in a cell, to return the value of the index and the column name:我有以下
df
如果单元格中有数值,则返回索引值和列名:
A B C
04/04/18 Nan Nan Nan
05/04/19 Nan 4 Nan
06/04/20 Nan Nan 5
With the output:随着输出:
["B-05/04/19","C-06/04/20"]
Is there any simple way I can iterate through rows and columns at the same time without the need of nested loops?有没有什么简单的方法可以在不需要嵌套循环的情况下同时遍历行和列?
If columns and index values are sorted use stack
with dropna
and last join MulitIndex
in list comprehension:如果对列和索引值进行排序,则使用带有
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']
Or get indices of non NaNs values, get values of indexing and join together:或者获取非 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')
Similar to jezrael's solution, but with numpy.argwhere
:类似于 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.