[英]How to count rows in a dataframe where column values match column values in another dataframe
我有以下樣本數據
df1 = [[52, '1', '10'], [54, '1', '4'],
[55, '2', '3'], [52, '1', '10'],
[55, '2', '10'], [52, '1', '4']]
df = pd.DataFrame(df1, columns =['Cow', 'Lact', 'Procedure'])
df2 = [['52', '1'], ['53', '9'],
['54', '2'], ['55', '2']]
df2 = pd.DataFrame(df2, columns =['Cow', 'Lact'])
這些表看起來像:
df
:
Cow Lact Procedure
0 52 1 10
1 54 1 4
2 55 2 3
3 52 1 10
4 55 2 10
5 52 1 4
df2
:
Cow Lact
0 52 1
1 53 9
2 54 2
3 55 2
我想計算df2
中每個Cow-Lact
組合的procedure = 10
,然后向df2
添加一個名為Tproc
的列,其中包含該計數。
我要找的output是
Cow Lact Tproc
0 52 1 2
1 53 9 0
2 54 2 0
3 55 2 1
以下過濾器不起作用:
filt = [(df['Cow']==df2['Cow'])&(df['Lact']==df2['Lact'])&(df['Procedure']==10)]
我當時的計划是使用.len
來計算
df2['Tproc'] = df2.loc[filt].len
如何根據另一個 DataFrame 中的值過濾一個 DataFrame 以統計滿足條件的行數?
你可以merge
+ groupby
+ sum
:
tmp = df2.merge(df.astype(str), on=['Cow','Lact'], how='left')
out = tmp['Procedure'].eq('10').groupby([tmp['Cow'], tmp['Lact']]).sum().reset_index(name='Tproc')
Output:
Cow Lact Tproc
0 52 1 2
1 53 9 0
2 54 2 0
3 55 2 1
您可以使用value_counts
並在 append 之前重新reindex
您的第一個 dataframe 到Tproc
列的值:
df2['Tproc'] = (
df1[df1['Procedure'] == '10'].value_counts(['Cow', 'Lact'])
.reindex(pd.MultiIndex.from_frame(df2[['Cow', 'Lact']]), fill_value=0).values
)
print(df2)
# Output
Cow Lact Tproc
0 52 1 2
1 53 9 0
2 54 2 0
3 55 2 1
設置:
df1 = pd.DataFrame({'Cow': [52, 54, 55, 52, 55, 52],
'Lact': [1, 1, 2, 1, 2, 1],
'Procedure': ['10', '4', '3', '10', '10', '4']})
df2 = pd.DataFrame({'Cow': [52, 53, 54, 55], 'Lact': [1, 9, 2, 2]})
使用groupby()
+ size()
然后merge()
out = df2.merge(
df[df['Procedure'] == '10'].groupby(['Cow', 'Lact']).size().reset_index(name='Tproc').astype(str),
how='left',
on=['Cow','Lact']
).fillna(0)
output:
Cow Lact Tproc 0 52 1 2 1 53 9 0 2 54 2 0 3 55 2 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.