[英]Row based Filter of a dataframe
I want to perform analysis on a dataframe. 我想对数据框执行分析。 This is my dataframe format. 这是我的数据框格式。
df_Input = pd.read_excel("/home/cc/Downloads/date.xlsx") df_Input = pd.read_excel(“ / home / cc / Downloads / date.xlsx”)
ID | BOOK | Type
-----------------------
1 | ABC | MAR
45 | PQR | TAB
45 | EDF | Fin
1 | DCF | oop
45 | PQR | TAB
I want to find count(count of every unique value) and unique values that each unique ID can hold. 我想找到计数(每个唯一值的计数)和每个唯一ID可以保存的唯一值。 The output should be a dataframe as shown below. 输出应为如下所示的数据框。
ID | BOOK_Count | Book_values |Type_count | Type_values
-----------------------------------------------------------
1 | 2 | [ABC,DCF] | 1 | [MAR,oop]
45 | 2 | [PQR,EDF] | 2 | [Fin,TAB]
I tried doing it but with a lot of loops. 我尝试这样做,但是有很多循环。 Thanks in advance 提前致谢
IIUC, you can use this: IIUC,您可以使用以下命令:
df_out = df.groupby('ID')['BOOK','Type'].agg(['nunique', lambda x: list(set(x))])
df_out = df_out.rename(columns={'nunique':'count', '<lambda>':'values'})
df_out.columns = df_out.columns.map('_'.join)
print(df_out)
OUtput: 输出:
BOOK_count BOOK_values Type_count Type_values
ID
1_1 2 [ABC, DCF] 2 [MAR, oop]
45_2 2 [EDF, PQR] 2 [TAB, Fin]
Let's say we have this dataframe : 假设我们有这个数据框:
ID BOOK type
0 1 ABC MAR
1 0 PQR TAB
2 1 EDF Fin
3 0 DCF oop
4 1 PQR TAB
You can use json
aggregate format as follow : 您可以使用json
聚合格式,如下所示:
aggreg = {
'BOOK':{
'BOOK_COUNT' : len,
'BOOK_values' : lambda r : r.tolist()
},
'type':{
'Type_COUNT' : len,
'Type_values' : lambda r : r.tolist()
}
}
Then, use groupby
: 然后,使用groupby
:
df.groupby('ID').agg(aggreg)
#output :
BOOK type
BOOK_COUNT BOOK_values Type_COUNT Type_values
ID
0 2 [PQR, DCF] 2 [TAB, oop]
1 3 [ABC, EDF, PQR] 3 [MAR, Fin, TAB]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.