I have a problem in selecting what columns to be inserted in Pandas.DataFrame.Groupby.agg.
Here’s the code to get and prepare the data.
JavaScript
x
19
19
1
# Data Collecting and library import
2
from pandas_datareader import data
3
import pandas as pd
4
5
symbol = 'AAPL'
6
source = 'yahoo'
7
start_date = '2018-01-01'
8
end_date = '2019-04-24'
9
stock = data.DataReader(symbol, source, start_date, end_date)
10
11
new_range = pd.date_range(start="2018-1-1", end="2019-12-30")
12
stock = stock.reindex(new_range).fillna(method='ffill').fillna(method='bfill')
13
stock['Day'] = stock.index.weekday_name
14
stock['Month'] = stock.index.month_name()
15
stock['Size'] = stock['High'].apply(lambda x: 'Big' if x>175 else 'Small')
16
stock['Other Size'] = stock['Low'].apply(lambda x: 'Big' if x>175 else 'Small')
17
stock.round(2)
18
stock.head(10)
19
Which results in
What I’ve done so far is
JavaScript
1
11
11
1
stock.groupby(['Day', 'Month']).agg(
2
{
3
'High' : [min, 'mean', max],
4
'Low' : [min, 'mean', max],
5
'Open' : 'mean',
6
'Size' : lambda x: x.value_counts().index[0],
7
# Other_non_numeric : lambda x: x.value_counts().index[1],
8
# Other_columns : 'mean'
9
}
10
).round(2)
11
that results in:
The question is:
- How do I include other non numeric columns?
- How do I include other undetermined columns in the dictionary and set the method as ‘mean’?
Advertisement
Answer
1) To determine if a column is numeric, you can use pandas.api.types.is_numeric_dtype
2) To find the remaining columns, you can use set(df.columns)
minus the columns you used in groupby
and those with specific agg functions, for example
JavaScript
1
12
12
1
from pandas.api.types import is_numeric_dtype
2
3
fields_groupby = ['Day', 'Month']
4
fields_specific = {
5
'High': [min, 'mean', max],
6
'Low': [min, 'mean', max],
7
'Open': 'mean',
8
'Size': lambda x: x.value_counts().index[0],
9
}
10
fields_other = set(set(stock.columns) - set(fields_groupby) - set(fields_specific))
11
fields_agg_remaining = {col: 'mean' if is_numeric_dtype(stock[col]) else lambda x: x.value_counts().index[1] for col in fields_other}
12
after that, combine the set of fields_specific
and fields_agg_remaining
to be the agg fields list
JavaScript
1
4
1
agg_fields = fields_agg_remaining
2
agg_fields.update(fields_specific)
3
stock.groupby(['Day', 'Month']).agg(agg_fields).round(2)
4
EDIT: You can combine everything to put them inside the dictionary argument, for example:
JavaScript
1
9
1
stock.groupby(['Day', 'Month']).agg(
2
{col:
3
[min, 'mean', max] if col in ['High', 'Low'] else
4
'mean' if col in ['Open'] else
5
lambda x: x.value_counts().index[0] if col in ['Size'] else
6
'mean' if is_numeric_dtype(stock[col]) else
7
lambda x: x.value_counts().index[1] for col in set(set(stock.columns) - {'Day', 'Month'})}
8
).round(2)
9