pandas 熊猫查找匹配值的行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48676872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas find Row number for matching values
提问by diogenes
I can find the matching row with this but how do I get the row number of the df?
我可以找到与此匹配的行,但是如何获取 df 的行号?
y = df.loc [ df [ 'month' ] == df3 [ 'month' ] ]
I need y to be the row count.
我需要 y 作为行数。
I can get the index value, but the index for df is also a date.
我可以获得索引值,但 df 的索引也是一个日期。
Thanks.
谢谢。
回答by 3novak
One method is reindexingsince you want the index to be integers rather than dates.
一种方法是重新索引,因为您希望索引是整数而不是日期。
y = df.loc[df['month'] == df3['month' ]].reset_index().index
回答by Guiem Bosch
If you don't want to reset the indexyou can simply add a column with a row count:
如果你不想重置索引,你可以简单地添加一个带有行数的列:
import pandas as pd
df = pd.DataFrame({'month':[1,1,1,1,2,2,2]})
df.insert(0, 'row_num', range(0,len(df))) # here you insert the row count
df3 = pd.DataFrame({'month':[2,2,2,1,2,2,2]})
y = df.loc [ df [ 'month' ] == df3 [ 'month' ] ]
The content of the df
的内容 df
>>> df
row_num month
0 0 1
1 1 1
2 2 1
3 3 1
4 4 2
5 5 2
6 6 2
Result
结果
>>> y['row_num']
3 3
4 4
5 5
6 6