Python中基于数据帧特征的计算?
我的数据框架如下所示:Python中基于数据帧特征的计算?,python,pandas,dataframe,aggregation,Python,Pandas,Dataframe,Aggregation,我的数据框架如下所示: df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"], "currency" : ["GBP", "GBP", "GBP", "CHF", "EUR&quo
df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"],
"currency" : ["GBP", "GBP", "GBP", "CHF", "EUR"],
"amount" : [100, 200, 300, 400, 500]})
我需要计算:
df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"],
"currency" : ["GBP", "GBP", "GBP", "CHF", "EUR"],
"amount" : [100, 200, 300, 400, 500]})
我们可以先进行筛选,然后再执行
groupby
和reindex
out = df.loc[df.currency=='GBP'].groupby(['ID']).amount.agg(['count','sum']).reindex(df.ID.unique())
Out[210]:
count sum
ID
1 1.0 100.0
2 2.0 500.0
3 NaN NaN
你可以试试这个-
import pandas as pd
df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"],
"currency" : ["GBP", "GBP", "GBP", "CHF", "EUR"],
"amount" : [100, 200, 300, 400, 500]})
>>> pd.pivot_table(df.loc[df.currency=='GBP'],index=["ID"],aggfunc={'currency':'count','amount':'sum'}).reindex(df.ID.unique()).reset_index()
ID amount currency
1 100.0 1.0
2 500.0 2.0
3 NaN NaN