Reputation: 21
I would like to add of the end of a Pandas Data frame a new row. The problem is that the tofpet_id and tofpet_channel have the same length but they are arrays and not single entries. So I would like to construct new rows, which consists of a single value for tofpet_id and tofpet_channel. For instance we have for row 10 tofpet_id =[1,2] and tofpet_channel=[3,4] and I would like to turn it into two different entries of tofpet_id = 1 and tofpet_channel=3 for the first and tofpet_id = 2 and tofpet_channel=4 for the second. I tried to do it using the code below, actually the temp line. But it doesnt work. Any ideas?
copy_df=df_ecal.copy()
copy_df['entry_id']=np.arange(copy_df.shape[0]) #done
test=df_ecal[df_ecal['n_hits']!=1]
for index,row in test.iterrows():
for j in range(len(row['tofpet_id'])): #Excellent
temp = test[row['tofpet_id'][j], row['tofpet_channel'][j], row['entry_id']]
# copy_df.append(temp,ignore_index=1)
print(row['tofpet_id'][j])
Upvotes: 0
Views: 817
Reputation: 303
EDITED
I miss-read in your case you just need to use the explode function built in pandas e.g.
import pandas as pd
data = {'Name':['Tom', 'Brad', 'Kyle', 'Jerry'],
'Age':[20, 21, 19, 18],
'Height' : [6.1, 5.9, 6.0, [6.1, 7.8]]
}
df = pd.DataFrame(data)
df.explode('Height')
# In your case you can explode with two columns like so:
df.explode(['Age', 'Height'])
# This will take the Nth element of both columns and make a new record.
That will do exactly what you want
From
To
Upvotes: 1