使用 Pandas 从循环输出中加入数据帧

我想从 for 循环输出的数据帧创建一个数据帧。循环的每次迭代都会产生名为 的变量result

 result = pd.concat([df1, df2], axis=1)

我想创建一个数据框,它是每个数据框的组合(彼此相邻)result

在循环之前我创建了一个变量combined_results

combined_results = pd.DataFrame()

在循环结束时,尝试使用 append、concat 等将每个结果存储在该变量中,但无法使其正常工作。

    combined_results = combined_results.append(result)

这垂直而不是水平附加并尝试 concat 按照result,但没有运气


胡子哥哥
浏览 89回答 2
2回答

忽然笑

pd.concat([...], axis=1)您在循环中使用的模式已经走在正确的轨道上。诀窍是将所有部分DataFrames 保存到一个列表中,然后将连接保存到最后。我使用这样的模式:combined_results = []for i in range(5):    df1 = pd.DataFrame({f'x{i}': ['a', 'b', 'c']})    df2 = pd.DataFrame({f'y{i}': [i, i*2, i*3]})    result = pd.concat([df1, df2], axis=1)    combined_results.append(result)# Use axis=1 as before to join horizontally instead of vertically.combined_results = pd.concat(combined_results, axis=1)combined_results#   x0  y0 x1  y1 x2  y2 x3  y3 x4  y4# 0  a   0  a   1  a   2  a   3  a   4# 1  b   0  b   2  b   4  b   6  b   8# 2  c   0  c   3  c   6  c   9  c  12

哈士奇WWW

在你的循环中,你可以这样做:df_results = [] for ... in ...:    result = pd.concat([df1, df2], axis=1)    df_results.append(result)df = pd.concat(df_results)如果您向我们展示您从哪里获得 df1 和 df2,也许我们可以改进这一点
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python