简体   繁体   English

如何轻松地同时遍历行和列?

[英]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.

相关问题 我如何遍历 python dict 并轻松到达叶子? - How can i iterate through a python dict and reach easily the leaves? 如何通过循环两次同时遍历文本文件 - how can I iterate through a text file by loop twice at the same time 如何同时遍历pandas的列和行? - How to iterate through pandas columns and rows simultaneously? 如何使用 Python 遍历 excel 中的列和行? - How to iterate through columns and rows in excel with Python? 如何使用 selenium 遍历网页表单行? - How can I iterate through rows of web form using selenium? 迭代行和列,python - Iterate through rows and columns, python 如何在数据框中迭代变量,同时通过另一个变量聚合并将标签分配为新变量? - How can I iterate through a variable in dataframe while the same time aggregating by another variable and assign labels as a new variable? 如何在列和行中同时进行循环以在数据帧的某些位置设置零? - How can I make a loop at the same time in columns and rows for setting a zero in some positions of the dataframe? 构建可以遍历行并从不同列中拉出的函数 - Building a function that can iterate through rows and pull from different columns 如何根据列中的唯一值最好地遍历 DataFrame 上的行? - How do I best iterate through rows on a DataFrame based on unique values in one of the columns?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM