首页 > 解决方案 > 迭代所有 Dataframe 行并执行startswith()

问题描述

我的 df 看起来像这样:

df

如您所见,用户以“ff”开头,它可能位于访问列或任何其他列而不是用户列中。

我想在这个 df 中创建一个名为“UserID”的新列,只要所有列中的 'ff' 都将这个值复制到我的新列“UserId”

我一直在使用这种工作正常的方法,但我必须在所有列中重复这一行:

hist.loc[hist.User.str.startswith("ff",na=False),'UserId']=hist['User'].str[2:]

有没有其他方法可以一次循环遍历所有行?

谢谢

标签: pythonpandasdataframe

解决方案


If you are cool with picking only the first occurence:

df['UserID'] = df.apply(lambda x: x[x.str.startswith('ff')][:1], axis=1)

推荐阅读