【问题标题】:How to append entire row using for loop for pandas dataframe如何使用for循环为熊猫数据框附加整行
【发布时间】:2020-01-05 03:57:25
【问题描述】:

我想使用 for 循环根据 if 语句条件附加整行。我的 for 循环只附加了一个特定的列,而不是全部附加。

我尝试给 append 两个参数,但它不起作用,因为它只接受一个参数。

android_clean = [] #lsit of new cleaned data
already_added = [] #list of the cleaned app names

for idx, row in android_data.iterrows():
    name  = row['App']
    n_reviews = float(row['Reviews'])

    if(reviews_max[name] == n_reviews)and (name not in already_added):
        android_clean.append(name)
        already_added.append(name) #make sure this inside the if block

len(android_clean)

一行包含 7 到 8 个不同的列。我的代码只附加了应用程序名称。我需要追加包括所有列在内的整行。

【问题讨论】:

    标签: python-3.x pandas for-loop data-cleaning


    【解决方案1】:

    追加行而不是行['App']。 该行是 itterrows() 中的整行。

    android_clean = [] #lsit of new cleaned data
    already_added = [] #list of the cleaned app names
    
    for idx, row in android_data.iterrows():
        name  = row['App']
        n_reviews = float(row['Reviews'])
    
        if(reviews_max[name] == n_reviews)and (name not in already_added):
            android_clean.append(row)
            already_added.append(name) #make sure this inside the if block
    
    len(android_clean)
    

    【讨论】:

      【解决方案2】:

      android_clean.append(name) 替换为android_clean.append(row)

      没有 for 循环:我建议你不要使用iterrows,而是更喜欢 Pandas 的内置函数,这些函数执行计算的效率更高。

      我假设reviews_max 是您代码中的字典,因为您使用名称作为键。这是一个两行代码,它应该为您提供与 for 循环相同的结果。

      max_reviews = android_data['App'].replace(reviews_max)
      android_clean = android_data.loc[row['Reviews'].astype('float') == max_reviews]\
                                  .drop_duplicates("App")
      

      【讨论】:

        猜你喜欢
        • 2015-10-18
        • 2017-02-13
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        相关资源
        最近更新 更多