如何使用函数和for循环比较数据帧中的两列?

2024-10-04 05:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个柱子,共两层

df = pd.DataFrame({"floor": [1,2,30], "floors_total": [1, 50, 30]})

我想写一个函数,比如如果在一行中,floors total和floor中的两个值相等,那么返回“last floor”,如果floor=1,那么返回“first floor”,如果other返回“other” 我想把这个应用到df

我正在尝试编写一个for循环,它是:

def new(df):
  a = "floor"
  b = "floors_total"
  for a,b in df.iteritems():
    if a == b:
      return "last floor"
    elif a == 1:
      return "first floor"
    else:
      return "other"
df["floor_postiton"] = df.apply(new)

我将新列中的所有行作为NaN


Tags: 函数dataframedfnewforreturndeftotal