【问题标题】:Function works on each row of data frame, but not using df.apply函数适用于数据框的每一行,但不使用 df.apply
【发布时间】:2018-10-25 16:05:17
【问题描述】:

我有这个熊猫数据框,每行包含两个样本 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')
    

我做错了什么?

【问题讨论】:

    标签: python python-3.x pandas scipy


    【解决方案1】:

    您只需要指定要在其上应用函数的轴。查看相关的docs 以获取apply()。简而言之,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
    

    【讨论】:

    • 啊当然!完全忘记了那里的轴。老实说,完全不清楚的错误信息也无济于事。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2017-09-20
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多