How To Add Multiple Different DataFrame Using For Loop?
I have multiple data frames and I want to add the values of the next data frame after the 3rd value of the previous data frame. I am very new with pyhton and I am using google cola
Solution 1:
Use pd.merge
df = df1.merge(df2.assign(Index=df2['Index']+3), how='outer') \
.merge(df3.assign(Index=df3['Index']+6), how='outer')
df['Column_2'] += df['Column_1'].fillna(0)
df['Column_3'] += df['Column_2'].fillna(0)
>>> df
Index Column_1 Column_2 Column_3
0 0 1.0 NaN NaN
1 1 1.0 NaN NaN
2 2 1.0 NaN NaN
3 3 1.0 3.0 NaN
4 4 1.0 3.0 NaN
5 5 1.0 3.0 NaN
6 6 NaN 2.0 5.0
7 7 NaN 2.0 5.0
8 8 NaN 2.0 5.0
9 9 NaN NaN 3.0
10 10 NaN NaN 3.0
11 11 NaN NaN 3.0
Update
Is there a way I can render the result in one column only?
df['Column_4'] = df.ffill(axis=1)['Column_3']
>>> df
Index Column_1 Column_2 Column_3 Column_4
0 0 1.0 NaN NaN 1.0
1 1 1.0 NaN NaN 1.0
2 2 1.0 NaN NaN 1.0
3 3 1.0 3.0 NaN 3.0
4 4 1.0 3.0 NaN 3.0
5 5 1.0 3.0 NaN 3.0
6 6 NaN 2.0 5.0 5.0
7 7 NaN 2.0 5.0 5.0
8 8 NaN 2.0 5.0 5.0
9 9 NaN NaN 3.0 3.0
10 10 NaN NaN 3.0 3.0
11 11 NaN NaN 3.0 3.0
Post a Comment for "How To Add Multiple Different DataFrame Using For Loop?"