尝试调试
这将以下内容放入我的标准输出:
groupby
函数应用时,有人建议我使用虚拟函数来“查看每个组传递了什么”进入该函数。当然,我愿意尝试:import numpy as np
import pandas as pd
np.random.seed(0) # so we can all play along at home
categories = list('abc')
categories = categories * 4
data_1 = np.random.randn(len(categories))
data_2 = np.random.randn(len(categories))
df = pd.DataFrame({'category': categories, 'data_1': data_1, 'data_2': data_2})
def f(x):
print type(x)
return x
print 'single column transform'
df.groupby(['category'])['data_1'].transform(f)
print '\n'
print 'single column (nested) transform'
df.groupby(['category'])[['data_1']].transform(f)
print '\n'
print 'multiple column transform'
df.groupby(['category'])[['data_1', 'data_2']].transform(f)
print '\n'
print '\n'
print 'single column apply'
df.groupby(['category'])['data_1'].apply(f)
print '\n'
print 'single column (nested) apply'
df.groupby(['category'])[['data_1']].apply(f)
print '\n'
print 'multiple column apply'
df.groupby(['category'])[['data_1', 'data_2']].apply(f)
这将以下内容放入我的标准输出:
single column transform
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
single column (nested) transform
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
multiple column transform
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
single column apply
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
single column (nested) apply
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
multiple column apply
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
看起来是这样的:
- 转换
- 单列:3个
Series
- 单列(嵌套):2个
Series
和3个DataFrame
- 多列:3个
Series
和3个DataFrame
- 单列:3个
- 应用
- 单列:3个
Series
- 单列(嵌套):4个
DataFrame
- 多列:4个
DataFrame
- 单列:3个
这里发生了什么?有人能解释一下为什么每个调用都会导致传递给指定函数的对象系列如上所述吗?