【发布时间】: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