【问题标题】:Iterate over one dataframe and add values to another dataframe without "append" or "concat"?迭代一个数据帧并将值添加到另一个数据帧而不“附加”或“连接”?
【发布时间】:2020-01-06 08:20:39
【问题描述】:

我有一个要迭代的数据框“df_edges”。 迭代内部是一个 if/else 和一个字符串拆分。我需要将 if/else 中的值添加到一个新的数据框中(每次迭代 = 另一个数据框中的一个新行)。

“df_edges”的示例数据:

+-----------------------------------------+
| channelId ... featuredChannelsUrlsCount |
+-----------------------------------------+
| 0  UC-ry8ngUIJHTMBWeoARZGmA  ... 1      |
| 1  UC-zK3cJdazy01AKTu8g_amg  ... 6      |
| 2  UC05_iIGvXue0sR01JNpRHzw  ... 10     |
| 3  UC141nSav5cjmTXN7B70ts0g  ... 0      |
| 4  UC1cQzKmbx9x0KipvoCt4NJg  ... 0      |

+-----------------------------------------+

# new empty dataframe where I want to add the values
df_edges_to_db = pd.DataFrame(columns=["Source", "Target"])

#iteration over the dataframe
for row in df_edges.itertuples():
    if row.featuredChannelsUrlsCount != 0:
        featured_channels = row[2].split(',')
        for fc in featured_channels:
            writer.writerow([row[1], fc])
            df_edges_to_db = df_edges_to_db.append({"Source": row[1], "Target": fc}, ignore_index=True)
    else:
        writer.writerow([row[1], row[1]])
        df_edges_to_db = df_edges_to_db.append({"Source": row[1], "Target": row[1]}, ignore_index=True)

这似乎有效。但是文档说(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html):

以下虽然不是推荐的生成 DataFrame 的方法

那么,是否有更“最佳实践”的方式(除了追加/连接)来添加具有值的行?

【问题讨论】:

    标签: pandas dataframe iterator append concat


    【解决方案1】:

    这里可以通过python append 创建字典列表,而不是像您的解决方案中的DataFrame.append,并且只调用一次DataFrame 构造函数:

    L = []
    #iteration over the dataframe
    for row in df_edges.itertuples():
        if row.featuredChannelsUrlsCount != 0:
            featured_channels = row[2].split(',')
            for fc in featured_channels:
                writer.writerow([row[1], fc])
                L.append({"Source": row[1], "Target": fc})
        else:
            writer.writerow([row[1], row[1]])
            L.append({"Source": row[1], "Target": row[1]})
    
    df_edges_to_db = pd.DataFrame(L)
    

    【讨论】:

      【解决方案2】:

      其实我不清楚你的 df_edges 数据框是什么样子的。通过查看您的代码,我建议您将外部 for 循环体替换为以下内容:

      new_list= [someOperationOn(x) if x==0 else otherOperationOn(x) for x in mylist]
      

      【讨论】:

      • 添加了 df_edges.head() 示例数据
      猜你喜欢
      • 2021-08-31
      • 2018-02-23
      • 2020-08-20
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多