【问题标题】:How to loop over selected columns in python pandas.如何遍历 python pandas 中的选定列。
【发布时间】:2015-08-07 06:31:33
【问题描述】:

我有一个数据框,其中包含这样命名的变量:

   exp1 exp2 exp3 
    10   20   56   

我有一个函数,它以 exp1 作为参数并创建一个名为 rate1 的变量。现在我想修改函数以循环 exp1 、 2 、 3 等并创建 rate1 、2 、3 等。我是 python 新手。完成这个简单任务的正确方法是什么。

【问题讨论】:

  • 通常,为了充分利用 pandas,您应该避免循环并尽可能“矢量化”您的操作/功能。这个问题很难给出一个好的答案,因为它在很大程度上取决于函数。如果您提供该功能,它将有所帮助。此外,您的示例数据框描述性不是很强,因为它只有一行,可以用熊猫系列来描述。不过我没有投票给你:)

标签: python python-2.7 pandas


【解决方案1】:

这应该可以,只需通过您的功能更改FUNCTION

rates = []
for column in df:
   # if your function deal with columns as dataframe
   rate = FUNCTION(df[column])
   rates.append(rate)

   # if your function deal with columns as lists
   rate = FUNCTION(df[column].values)
   rates.append(rate)

   # if your dataframes contain one value (row) and your function deal with this values as floats
   rate = FUNCTION(float(df[column].values))
   rates.append(rate)
print rates

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-08
    • 2016-10-06
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2019-03-28
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多