【问题标题】:How to get value from specific column in 1 row using Python Pandas?如何使用 Python Pandas 从 1 行中的特定列中获取值?
【发布时间】:2021-02-07 07:59:07
【问题描述】:

我正在学习 Python Pandas,我的任务是基于 .csv 文件生成生成器。生成器必须实现为在 for 循环中调用并从第一列、第二列和最后一列返回值的函数。要从函数返回值,我必须使用 yield 关键字。我写了这样的东西:

def patient_reader(data_frame): #sa - still alive, a -age, ms - months survived
    sa = data_frame['still_alive']
    a = data_frame['age']
    ms = data_frame['months_survived']
    yield sa,a,ms

但我不知道如何将它实现到 for 循环中。你对我有什么建议吗? 如何将产生的值存储在元组或列表中?

【问题讨论】:

  • 见iloc。然后,您只需要对系列长度(又名列)的整数进行循环。有一种更短的方法,但需要更多地了解 Python、迭代器和 pandas。

标签: python pandas csv generator yield


【解决方案1】:
# try this
def patient_reader(data_frame): #sa - still alive, a -age, ms - months survived
    res_list = []
    for row in data_frame.iterrows():
        sa = row['still_alive']
        a = row['age']
        ms = row['months_survived']
        res_list.append((sa, a, ms))
    yield res_list

【讨论】:

  • 我认为生成器应该分别从每一行产生项目。
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 2020-09-25
  • 2020-09-25
相关资源
最近更新 更多