names Class Category label
ram A Red one
ravi A Red two
gopal B Green three
Sri C Red four
my_list1=["Category"]
my_list2=["Class"]
I need to get the combination counts between these two columns.
I am trying to get the combination of some selected columns. my_list2 even have more than one.
I tried,
df[mylist1].value_counts()
It is working fine for a sinigle column. But I want to do for multiple column in my_list2 based on my_list1
My desired output should be,
output_df,
Value Counts
Red.A 2
Red.C 1
Green.B 1
I think you need join both lists first, then create Series
and last value_counts
:
print (df)
names Class Category label Class1
0 ram A Red one E
1 ravi A Red two G
2 gopal B Green three B
my_list1=["Category"]
my_list2=["Class", "Class1"]
df = df[my_list1 + my_list2].apply('.'.join, axis=1).value_counts()
print (df)
Red.A.E 1
Red.A.G 1
Green.B.B 1
dtype: int64
Detail:
print (df[my_list1 + my_list2])
Category Class Class1
0 Red A E
1 Red A G
2 Green B B
print (df[my_list1 + my_list2].apply('.'.join, axis=1))
0 Red.A.E
1 Red.A.G
2 Green.B.B
dtype: object
You can use str.cat
like
In [5410]: my_list1 = ["Category"]
...: my_list2 = ["Class", "Class1"]
In [5411]: df[my_list1+my_list2].apply(lambda x: x.str.cat(sep='.'), axis=1).value_counts()
Out[5411]:
Green.B.B 1
Red.A.E 1
Red.A.G 1
dtype: int64
Also
In [5516]: pd.Series('.'.join(x) for x in df[my_list1 + my_list2].values).value_counts()
Out[5516]:
Green.B.B 1
Red.A.E 1
Red.A.G 1
dtype: int64
Or
In [5517]: pd.Series(map('.'.join, df[my_list1 + my_list2].values)).value_counts()
Out[5517]:
Green.B.B 1
Red.A.E 1
Red.A.G 1
dtype: int64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.