Yugo Harago
Yugo Harago

Reputation: 341

py pandas row iterate add new data in a duplicated row 1-1 1-n

I don't know how to explain exactly. But let's go to an example:
I have this dictionaries

dictData = {'movie_id':[11,12,13],'title':['filmA','filmB','filmC']}
dictFilm = {'filmA': ['pathA1\\ImageA1.jpg','pathA2\\ImageA2.jpg'],
            'filmB': ['pathB1\\ImageB1.jpg','pathB2\\ImageB2.jpg'],
            'filmC':['pathC1\\ImageC1.png','']}

And from these, I will make a new data

dfData = pd.DataFrame.from_dict(dictData)
dfFilm = pd.DataFrame.from_dict(dictFilm)

to_image_df = pd.DataFrame.from_dict({})

for i, row in dfFilm.iterrows():
    to_image_df.at[i,'movie_id'] = int(dfData.at[i,'movie_id'])
    to_image_df.at[i,'name']     = dfData.at[i,'title']
    to_image_df.at[i,'path']     = dfFilm.at[i,'filmB']
print(to_image_df.head())

This gives me this result:

   movie_id   name                path
0      11.0  filmA       pathB1\B1.jpg
1      12.0  filmB  pathB2\ImageB2.jpg

but I want result like this:

   movie_id   name                 path
0      11.0  filmA  pathA1\\ImageA1.jpg
1      11.0  filmA  pathA2\\ImageA2.jpg
2      12.0  filmB   pathB2\ImageB1.jpg
3      12.0  filmB   pathB2\ImageB2.jpg
4      13.0  filmC   pathC1\ImageC1.png

Upvotes: 2

Views: 43

Answers (2)

BENY
BENY

Reputation: 323236

Using melt with merge

dfFilm = dfFilm.melt().loc[lambda x : x['value']!='']
df = dfData.merge(dfFilm,left_on='title',right_on='variable',how='right').drop('variable',1)
df
Out[277]: 
   movie_id  title               value
0        11  filmA  pathA1\ImageA1.jpg
1        11  filmA  pathA2\ImageA2.jpg
2        12  filmB  pathB1\ImageB1.jpg
3        12  filmB  pathB2\ImageB2.jpg
4        13  filmC  pathC1\ImageC1.png

Upvotes: 2

cs95
cs95

Reputation: 402513

map and flatten/expand.

df = pd.DataFrame(dictData)
v = df.title.map(dictFilm) 

df = (pd.DataFrame(df.values.repeat(v.str.len(), axis=0), columns=df.columns)
        .assign(path=list(chain.from_iterable(v)))
        .replace('', np.nan)
        .dropna(subset=['path']))

df
   movie_id  title                path
0        11  filmA  pathA1\ImageA1.jpg
1        11  filmA  pathA2\ImageA2.jpg
2        12  filmB  pathB1\ImageB1.jpg
3        12  filmB  pathB2\ImageB2.jpg
4        13  filmC  pathC1\ImageC1.png

Upvotes: 2

Related Questions