I have one dataframe (df1
):
I then create a new dataframe (df2
) which has twice as many rows as fd1
. My goal is to copy some elements of the first dataframe inside the second one in a smart way so that the result looks like this:
So far I was able to reach this goal by using the following commands:
raw_data = {'A': ['pinco', 'pallo', 'pollo'],
'B': ['lollo', 'fallo', 'gollo'],
'C': ['pizzo', 'pazzo', 'razzo']}
df1 = pd.DataFrame(raw_data, columns = ['A', 'B', 'C'])
columns = ['XXX','YYY', 'ZZZ']
N = 3
df2 = pd.DataFrame(columns=columns,index=range(N*2))
idx = 0
for i in range(N):
df2['XXX'].loc[idx] = df1['A'].loc[i]
df2['XXX'].loc[idx+1] = df1['A'].loc[i]
df2['YYY'].loc[idx] = df1['B'].loc[i]
df2['YYY'].loc[idx+1] = df1['C'].loc[i]
idx += 2
However I am looking for a more efficient (more compact and elegant) way to obtain this result. I tried to use the following combination inside of the for loop without success:
df2[['XXX','YYY']].loc[idx] = df1[['A', 'B']].loc[i]
df2[['XXX','YYY']].loc[idx+1] = df1[['A', 'C']].loc[i]