[英]How to get the index of the first non-zero value for a pandas dataframe column
我正在尝试获取 pandas dataframe 的特定列的第一个非零值的索引。
import pandas as pd
df = pd.DataFrame(
[[0,0,0],
[0,0,3],
[1,5,7],
[8,7,3]],
columns=['c1','c2','c3'])
print(df)
Output:
c1 c2 c3
0 0 0 0
1 0 0 3
2 1 5 7
3 8 7 3
我想在 c2 列中获得值为 5(第一个非零值)的索引 position。
您可以将boolean 索引与first_valid_index
结合使用:
df.loc[df['c2'].ne(0), 'c2'].first_valid_index()
output: 2
注意。 如果列中只有零,则 output 将为None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.