[英]Pandas dataframe split or groupby dataframe at each occurence of value (True) in column
有一个这样的 df:
df = pd.DataFrame({'words':['hi', 'this', 'is', 'a', 'sentence', 'this', 'is', 'another', 'sentence'], 'indicator':[1,0,0,0,0,1,0,0,0]})
这给了我:
words indicator
0 hi 1
1 this 0
2 is 0
3 a 0
4 sentence 0
5 this 1
6 is 0
7 another 0
8 sentence 0
现在我想合并“words”列的所有值,这些值跟在指示器中的“1”之后,直到下一个“1”出现。 这样的事情将是理想的结果:
words indicator counter
0 hi this is a sentence 1 5
1 this is another sentence 1 4
解释起来并不容易,这就是我依赖这个例子的原因。 我尝试了 groupby 和 split,但无法找到解决方案。 最后一次尝试是设置某种 df.iterrows(),但我现在想避免这种情况,因为实际的 df 非常大。
在此先感谢您的帮助!
您可以获得指标的累积总和,然后将其分组以将所有单词连接到一个空格上并计算每个句子中的单词数。
df["indicator"] = df["indicator"].cumsum()
df = df.groupby(
"indicator", as_index=False
).agg(
words=("words", " ".join),
counter=("indicator", "size")
)
# indicator words counter
# 0 1 hi this is a sentence 5
# 1 2 this is another sentence 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.