Analyzing a dataframe based on multiple conditions

家住魔仙堡 提交于 2019-12-24 19:14:58

问题


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

回答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



回答2:


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


来源:https://stackoverflow.com/questions/46907847/analyzing-a-dataframe-based-on-multiple-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!