函数适用于数据帧的每一行,但不使用df.apply

时间:2018-05-15 18:06:50

标签: python python-3.x pandas scipy

我有这个pandas数据帧,每行包含两个样本X和Y:

import pandas as pd
import numpy as np
df = pd.DataFrame({'X': [np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10)],
                   'Y': [np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10),
                         np.random.normal(0, 1, 10)]})

我想在每一行上使用一个函数ttest_ind()(一个统计测试,将两个样本作为输入),然后获取响应的第一个元素(该函数返回两个元素):

  • 如果我为给定的行执行此操作,例如第一行,它的工作原理:

    from scipy import stats
    stats.ttest_ind(df['X'][0], df['Y'][0], equal_var = False)[0]
    # Returns a float
    
  • 但是,如果我使用apply在每一行上执行,我会收到错误:

    df.apply(lambda x: stats.ttest_ind(x['X'], x['Y'], equal_var = False)[0])
    
    # Throws the following error:
    Traceback (most recent call last):
    File "pandas\_libs\index.pyx", line 154, in 
    pandas._libs.index.IndexEngine.get_loc
    File "pandas\_libs\hashtable_class_helper.pxi", line 759, in 
    pandas._libs.hashtable.Int64HashTable.get_item
    TypeError: an integer is required
    During handling of the above exception, another exception occurred:
    ...
    KeyError: ('X', 'occurred at index X')
    

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您只需指定要应用功能的轴。查看apply()的相关docs。简而言之,axis = 1表示“将函数应用于我的数据帧的每一行”。默认值为axis = 0,它会尝试将函数应用于每列。

df.apply(lambda x: stats.ttest_ind(x['X'], x['Y'], equal_var = False)[0], axis=1)

0    0.985997
1   -0.197396
2    0.034277