【问题标题】:Error in Iterating through Pandas DataFrame with if statement使用 if 语句迭代 Pandas DataFrame 时出错
【发布时间】:2020-10-14 21:40:41
【问题描述】:

我有以下 pandas DataFrame。

   Id UserId    Name            Date                 Class  TagBased
0   2   23  Autobiographer  2016-01-12T18:44:49.267     3   False
1   3   22  Autobiographer  2016-01-12T18:44:49.267     3   False
2   4   21  Autobiographer  2016-01-12T18:44:49.267     3   False
3   5   20  Autobiographer  2016-01-12T18:44:49.267     3   False
4   6   19  Autobiographer  2016-01-12T18:44:49.267     3   False

我想遍历“TagBased”列并将用户 ID 放入 TagBased=True 的列表中。 我使用了以下代码,但没有得到不正确的输出,因为 TagBased 中有 18 个 True 值。

user_tagBased = []

for i in range(len(df)):
    if (df['TagBased'] is True):
        user_TagBased.append(df['UserId'])
print(user_TagBased)

Output: []

【问题讨论】:

  • 试试 df.loc[df['TagBased'],'UserId'].tolist() 你在 pandas 中大部分时间都不需要循环
  • 尝试此方法时出现以下错误: KeyError: "None of [Index(['False', 'False', 'False', 'False', 'False', 'False ', '假', '假',\n '假', '假',\n ...\n '假', '假', '假', '假', '假', '假' , 'False', 'False',\n 'False', 'False'],\n dtype='object', length=18087)] 在 [index]"
  • df.loc[df['TagBased'].eq("True"),'UserId'].tolist() 更好,因为值是字符串
  • 这个有效,非常感谢!!

标签: python-3.x pandas loops dataframe iteration


【解决方案1】:

正如其他人所建议的那样,使用 Pandas 条件过滤是最好的选择,而不使用循环!但是,仍然要解释为什么您的代码没有按预期工作:

您在 for 循环中附加 df['UserId'],而 df['UserId'] 是一列。 df['TagBased'] 检查也是如此,它也是一个列。

我假设你想在 for 循环的当前行追加 userId。

您可以通过遍历 df 行来做到这一点:

user_tagBased = []

for index, row in df.iterrows():
    if row['TagBased'] == 'True': # Because it is a string and not a boolean here
        user_tagBased.append(row['UserId'])

【讨论】:

    【解决方案2】:

    试试这个,你不需要为此使用循环:

    user_list = df[df['TagBased']==True]['UserId'].tolist()
    print(user_list)
    
    [19, 19]
    

    【讨论】:

      【解决方案3】:

      没有必要使用任何循环。

      注意:

      • df.TagBased - 产生 bool 类型的 Series - TagBased 列 (我假设 TagBased 列是 bool 类型)。
      • df[df.TagBased] - 是 布尔索引 的示例 - 它检索 TagBasedTrue 的行
      • df[df.TagBased].UserId - 将上述结果限制为 UserId, 几乎是你想要的,但这是一个系列,而你想要一个 列表

      所以生成预期结果的代码,并保存在目标中 变量,是:

      user_tagBased = df[df.TagBased].UserId.to_list()
      

      【讨论】:

        猜你喜欢
        • 2021-06-26
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-05-19
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 2015-02-14
        相关资源
        最近更新 更多