我有一些Word文档,在读入数据框之前将其转换为字符串。每个数据帧只有一列宽,但有很多行长。它们都看起来像这样:
0| this document is a survey
1| please fill in fully
2| Send back to address on the bottom of the sheet
etc....
每个数据帧的开头都是乱码,我不需要,所以我需要删除包含值“ Questions”的行之前的所有行。但是,它并不位于每个数据帧相同的索引上,因此我不能只删除前20行,因为它将对每个数据帧产生不同的影响。
如何删除每个数据框中“问题”之前的所有行
答案 0 :(得分:0)
假设您只需要在第一次出现“问题”之后保留行,那么这种方法应该可以解决问题:
import pandas as pd
data = {
'x': [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'
]
}
df = pd.DataFrame(data)
df
输出:
x
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
在这里,我将保留第一次出现以字母'f'开头的条目之后的所有行:
df[df.x.str.startswith('f').cumsum() > 0]
输出:
x
5 f
6 g
7 h
8 i
9 j
10 k
该解决方案依赖于两个主要的pandas
功能:
pd.DataFrame().str.startswith
,对于以给定字符串开头的任何单元格,使用True
获取布尔数组(在此示例中为'f',但'Questions'也将起作用)。cumsum()
会将布尔值转换为整数,因此请确保首次出现后的所有行都大于零。通过使用这些索引原始数据帧,我们获得了解决方案。
答案 1 :(得分:0)
另一种替代方法是使用str.contains()
。使用玩具熊猫系列:
import pandas as pd
# create dataframe
d = ["nothing", "target is here", "help", "more_words"]
df = pd.Series(data=d)
如果您想保留一个单词后的所有行(包括所有行),请说“这里”,您可以这样做:
# check rows to determine whether they contain "here"
keyword_bool = df.str.contains("here", regex=False)
# return index as int
idx = keyword_bool[keyword_bool==True].index[0]
# slice dataframe
df = df.iloc[idx:]