如何从包含给定字符串的行开始对两列数据帧进行切片?

2024-10-03 19:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

df = pd.DataFrame({'A':['A','B','C','D'],
                   'B':[4,5,6,7]})

A B
A 4
b5
C 6
第7天

我想返回一种方法来返回从给定字符串开始的所有行,比如a列中的“B”

A B
b5
C 6
第7天

去死吧!你知道吗


Tags: 方法字符串dataframedfpdb5去死吧
3条回答

如果字符串始终存在,可以使用idxmax()和条件序列来查找字符串第一次出现的索引,然后使用tail()方法提取索引后的行:

df.tail(-(df.A == "B").idxmax())   # this method works if the string exists in the column
# and the index of the data frame is a normal sequence as given by range(n)

#   A   B
#1  B   5
#2  C   6
#3  D   7

另一种可能更安全的方法,即使列中不存在字符串,也仍然有效:

df[(df.A == "B").cumsum().astype(bool)]  

#   A   B
#1  B   5
#2  C   6
#3  D   7

假设A列中的数据是按字母顺序排序的,您可以使用子集,这类似于

df[df['A'] >= 'B']

会成功的。你知道吗

一个概括得很好的答案可以使用numpy.argwhere

idx = np.argwhere(df.A == 'B')[0][0]
df.iloc[idx:]

相关问题 更多 >