2 回答

TA貢獻1806條經(jīng)驗 獲得超5個贊
pd.concat([...], axis=1)您在循環(huán)中使用的模式已經(jīng)走在正確的軌道上。訣竅是將所有部分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

TA貢獻1799條經(jīng)驗 獲得超6個贊
在你的循環(huán)中,你可以這樣做:
df_results = []
for ... in ...:
result = pd.concat([df1, df2], axis=1)
df_results.append(result)
df = pd.concat(df_results)
如果您向我們展示您從哪里獲得 df1 和 df2,也許我們可以改進這一點
添加回答
舉報