简体   繁体   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

Now I have a dataframe:现在我有一个 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

I want to go through all of the cells in the last column and try to find the first cell with currency formatting.我想通过最后一列中的所有单元格 go 并尝试找到第一个具有货币格式的单元格。 The first desired cell is df['C'][2].第一个所需的单元格是 df['C'][2]。 The row index I want to return is 2.我要返回的行索引是 2。

IIUC, you could do the following: IIUC,您可以执行以下操作:

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

Output Output

2

It works as follows:它的工作原理如下:

  • df.iloc[:, -1] select the last column df.iloc[:, -1] select 最后一列
  • .str.match(r'^\$\d+') use match to create a boolean array, True if matches the currency formatting. .str.match(r'^\$\d+')使用match创建一个 boolean 数组,如果匹配货币格式则为真。
  • .idxmax() in Python True -> 1 and False -> 0, so idxmax will find the maximum value in the array, if there are multiple it will return the first. .idxmax() True -> 1 和 False -> 0,所以 idxmax 会在数组中找到最大值,如果有多个它将返回第一个。 See more on the documentation .查看文档的更多信息。

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

相关问题 pandas dataframe python - 使第一行成为最后一行 - pandas dataframe python - make the first row to be the last 获取带索引的 pandas dataframe 第一行 - Get the pandas dataframe first row with index Excel 到 Pandas DataFrame 使用第一列作为索引 - Excel to Pandas DataFrame using first column as index 为什么我的 pandas dataframe 索引的第一行是索引列的名称? - Why is the first row of my pandas dataframe index the name of the index column? Pandas 数据框获取掩码列的零(0)之间的所有行,并获取每组的第一行和最后一行 - Pandas dataframe get all rows between zero(0) of mask column and get first and last row of each group 如何删除熊猫数据框的最后一列中的第一个值,然后删除其余的最后一行? - How to delete first value in the last column of a pandas dataframe and then delete the remaining last row? Python Pandas:如何从数据帧的索引中获取行名? - Python Pandas: How to get the row names from index of a dataframe? 如何在熊猫中设置第一列和第一行作为索引? - How to set in pandas the first column and row as index? 如何使用函数从dataframe列获取第一个和最后一个值 - How to get the first and last values from the dataframe column using a function 熊猫按行号(不是行索引)和列名获取单元格值 - Pandas get cell value by row NUMBER (NOT row index) and column NAME
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM