我有两个(或更多)循环,并在每个循环内创建一个 DF。我想在新的 DF 中显示以下结果。我尝试编写以下代码:
table = pd.DataFrame(columns=['col_x', 'col_y', 'col_3', 'predict'])
for x in ['a', 'b', 'c']:
for y in ['d', 'e', 'f']:
filtered_df = df[(df[col_1] == x) & (df[col_2] == y)]
s1 = filtered_df[col_3]
s2 is a serie (predictions after linear regression with this filtered_df)
table['col_x'] = [x]*len(filtered_df)
table['col_y'] = [y]*len(filtered_df)
table['col_3'] = s1
table['predict'] = s2
因此,在第一个循环中,我希望在“table”的最后两列中有系列“s1”和“s2”。前两列具有相同的数据(第一个循环中的“a”和“d”)。
在下面的循环中我想完成我的表格。每个环可以有不同的长度。
我不知道如何附加数据帧(或像 SQL 中那样进行联合)。另外,我分配列的方式不起作用。
提前谢谢您。
为了“联合”两个数据框,请尝试
pd.concat
。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html
例如
df_union = pd.concat([df1,df2])