0

I have a function foo() with input parameter dataframe that counts each value large 1. So a dataframe 400x5 gets reduced to 1x5.

Now I have a dataframe like

Country    Value1    Value2
US         1         3
Uk         3         2
US         2         1
UK         5         5

The result could look like

Country    Value1    Value2
US         1         1 
Uk         2         2

My goal is to split the dataset by country and perform my foo(). I found a solution to split the dataset with groupby() but groupby gives me tuples back and not dataframes what is a problem since my foo() only eats dataframes. Does anyone have an idea how I can split my dataframe into dataframes and perform my funtion on them?

ruedi
  • 5,365
  • 15
  • 52
  • 88

1 Answers1

1
import pandas as pd
from pandas.compat import StringIO
print(pd.__version__)

data =  """Country    Value1    Value2
US         1         3
UK         3         2
US         2         1
UK         5         5"""

df = pd.read_csv(StringIO(data), sep='\s+')
df = df.groupby('Country').apply(lambda x: x.where(x > 1).count())
print(df)

Produces

0.24.2
         Value1  Value2
Country                
UK            2       2
US            1       1

Note, the countries are treated in a case sensitive manner, the Q contains mixed case, the answer does not.

Rich Andrews
  • 1,590
  • 8
  • 12