【问题标题】:Python: Referencing a column in DataFrame using a functionPython:使用函数引用 DataFrame 中的列
【发布时间】:2021-05-12 17:53:28
【问题描述】:

这是我的代码:

.......

gender = data.loc[np.where(data['ID']==id)]["gender"].tolist()[0]
cell = data.loc[np.where(data['ID']==id)]["cell"].tolist()[0]
bloodtype = data.loc[np.where(data['ID']==id)]["bloodType"].tolist()[0]

expList = tempPos[(tempPos.gender == gender) & (tempPos.cell == cell) & (tempPos.bloodType == bloodtype)]

.......

现在还有几个其他列可以在 tempPos 数据框中引用(在上面的示例中,我使用了性别、细胞和血型)

有没有一种方法可以定义函数并动态引用列?

def generateProbability(col1, col2, col3):
    .......
    col1val = data.loc[np.where(data['ID']==id)][col1].tolist()[0]
    col2val = data.loc[np.where(data['ID']==id)][col2].tolist()[0]
    col3val = data.loc[np.where(data['ID']==id)][col3].tolist()[0]
    expList = tempPos[(tempPos.col1 == col1val) & (tempPos.col2 == col2val) & (tempPos.col3 == col3val)]
    ........

generateProbability("Age","Gender","bloodType")

谢谢。

【问题讨论】:

  • 为什么不把data.loc[np.where(data['ID'] == id)]["cell"]改成data.loc[data['ID'] == id, "cell"]

标签: python dataframe dynamic-columns


【解决方案1】:

您无需创建函数。您可以通过 for 循环访问它们。

column_outputs = dict    # Dictionary to hold column outputs.

for column in data.columns:
    column_outputs[column] = data.loc[data['ID'] == id, column].tolist()[0]

column_outputs 现在应该包含每列所需的值,您可以使用列名作为键来访问这些值。

【讨论】:

  • 我的错,下面的代码没有问题: col1val = data.loc[np.where(data['ID']==id)][col1].tolist()[0]我需要帮助的部分在这里 - expList = tempPos[(tempPos.col1 == col1val),因为 tempPos.col1 不存在 - 引用需要是动态的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 2012-06-12
  • 2021-07-14
  • 2015-07-25
  • 2013-11-30
相关资源
最近更新 更多