用不同长度的DF拼接Python
我有两个(或者更多)循环,每个循环里面我都会创建一个数据框(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
在第一个循环中,我想把系列's1'和's2'放在'table'的最后两列。而前两列则是相同的数据(在第一个循环中是'a'和'd')。
在接下来的循环中,我想继续填充我的表格。每个循环的长度可能不同。
我不知道怎么把数据框合并(或者像SQL那样做联合)。而且,我设置列的方式也没有成功。
谢谢大家的帮助。
1 个回答
0
为了把两个数据表合并在一起,可以试试用 pd.concat
。你可以在这里找到更多信息:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html
例如:
df_union = pd.concat([df1,df2])