![](/img/trans.png)
[英]How do I slice a row and the preceding row based on two column values in pandas?
[英]How do I slice a two column pandas dataframe starting with a row containing a given string?
df = pd.DataFrame({'A':['A','B','C','D'],
'B':[4,5,6,7]})
AB
A 4
B 5
C 6
第7天
我想返回一種方法,以返回從給定字符串開始的所有行,在A列中說“ B”。
AB
B 5
C 6
第7天
去死神!
如果字符串始終存在,則可以對條件Series使用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']
會成功的
如果A
列未按字母順序排序,則可以使用此解決方案。
而且,當這將開始從該行的數據幀B
用於在列中的第一次出現A
,如果列A
包含一個以上的值B
。
idx = df[df['A'] == 'B'].index[0]
df = df[idx:]
print(df)
A B
1 B 5
2 C 6
3 D 7
概括性很好的答案可以使用numpy.argwhere
idx = np.argwhere(df.A == 'B')[0][0]
df.iloc[idx:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.