繁体   English   中英

如何使用 Python Pandas 在 dataframe 的最后一列中获取第一个具有货币格式的单元格的行索引

[英]How to get the row index of the first cell with currency formatting in the last column of a dataframe using Python Pandas

现在我有一个 dataframe:

import pandas as pd

s1 = pd.Series(['a', 'b', 'c'])
s2 = pd.Series(['e', '$200', 'f'])
s3 = pd.Series(['e', '$300', '$400'])
s4 = pd.Series(['f', '$500', '$600'])
    
df = pd.DataFrame([list(s1), list(s2), list(s3), list(s4)],  columns =  ['A', 'B', 'C'])
df

    A   B   C
0   a   b   c
1   e   $200    f
2   e   $300    $400
3   f   $500    $600

我想通过最后一列中的所有单元格 go 并尝试找到第一个具有货币格式的单元格。 第一个所需的单元格是 df['C'][2]。 我要返回的行索引是 2。

IIUC,您可以执行以下操作:

df.iloc[:, -1].str.match(r'^\$\d+').idxmax()

Output

2

它的工作原理如下:

  • df.iloc[:, -1] select 最后一列
  • .str.match(r'^\$\d+')使用match创建一个 boolean 数组,如果匹配货币格式则为真。
  • .idxmax() True -> 1 和 False -> 0,所以 idxmax 会在数组中找到最大值,如果有多个它将返回第一个。 查看文档的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM