[英]Pandas: how to calculate a rolling window over one column (grouped by date) and count distinct values of another column?
[英]How to count consecutive string values of one column grouped by column values of another in a dataframe?
我有以下 dataframe:
|Levels|Labels|Confidence|
|----------------------------
|0. | Hands | 0.8
|0 |Leg | 0.7
|0 |Eye. | 0.9
|1 |Ear |0.9
|1 |Eye. |0.8
|2 |Hands |0.9
|2 |Eye. |0.8
|3. |Eye. |0.8
:
:
:
我想檢查我的任何標簽是否連續出現在我的級別(0、1、2、3、4、5 ..)以及有多少連續級別(我的每個身體部位的此類連續級別的計數)。 這是我的示例數據集,您可以看到 label “眼睛”連續出現 4 個級別,“手”連續出現 1..等。
這里有一個類似的問題: How to find the count of continuous same string values in a pandas dataframe?
在那里修改此解決方案對我不起作用。 我還嘗試將其轉換為同樣不起作用的 NumPy 數組。
你能看看這個嗎?
這應該有效。 只需定義自定義聚合 function。
import pandas as pd
df = pd.DataFrame({
'lvl': [0, 0, 0, 1, 1, 2, 2, 3, 3, 3, 4],
'label': ['a', 'b', 'c', 'a', 'b', 'a', 'c', 'a', 'b', 'c', 'c'],
'confidence': [0.1, 0.5, 0.3, 0.6, 0.2, 0.4, 0.7, 0.8, 0.5, 0.2, 0.8]
})
agg_func = {
'lvl': [('length', lambda x: x.ne((x+1).shift()).cumsum().value_counts().max())]
}
result = df.groupby('label').agg(agg_func)
result.columns = result.columns.droplevel(0)
print(result)
length
label
a 4
b 2
c 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.