【问题标题】:Applying a function to multiple columns in a list将函数应用于列表中的多个列
【发布时间】:2022-10-14 23:24:17
【问题描述】:

我有很多列要应用相同的功能。

cols=['a','b','c','d']

def cols_1(x):
    if x[c]=="5: Very important":
        return 5
    if x[c]== "1: Not at all important":
        return 1      
    else:
        return x

for c in cols:
    df[c]=df[c].apply(cols_1)   

我已经尝试了上述的许多变体,但没有一个有效。我究竟做错了什么?

【问题讨论】:

  • 你是什​​么意思“没有工作”?运行代码时会发生什么?你有错误吗?如果是这样,请edit您的问题并附上完整的错误消息。如果不是,输出是什么?请edit你的问题包括它。然后描述输出与您想要的有何不同。
  • 该函数不需要使用[c]。你在写df[c] 时已经这样做了

标签: python pandas


【解决方案1】:

您可以将函数应用于df 中的每一列,如下所示:

def cols_1(x):
if x == "5: Very important":
    return 5
if x == "1: Not at all important":
    return 1      
else:
    return x

for c in cols:
    df[c] = cols_1(df[c])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2013-11-28
    • 1970-01-01
    • 2019-09-13
    • 2015-06-19
    • 2013-01-09
    相关资源
    最近更新 更多