How To Fill The Values In The List And Convert It Into The Dataframe?(part Ii)
I have a modified data frame from the previous question: How to fill the values in the list and convert it into the dataframe? Item Photo1 Photo2 Photo3 Photo4 De
Solution 1:
Use:
#created default indexdf = df.reset_index(drop=True)
df1 = df.reindex(df.columns.tolist() + ['I','PH','Descr'], axis=1)
df1['I'] = df1['I'].fillna('I')
#added column not called Description
df1['Descr'] = df1['Descr'].fillna('Description')
df1['PH'] = df1['PH'].fillna('PH')
#added values like input data
vals = [['I','Item']]
print (df1)
Item Photo1 Photo2 Photo3 Photo4 Description1 Description2 Description3 \
0 A A1.jpg A2.jpg NaN NaN Nice Beautiful NaN
1 B B1.jpg B2.jpg B3.jpg B4.jpg Ugly Damaged NaN
2 C C1.jpg NaN NaN NaN Cute Handsome Nice
I PH Descr
0 I PH Description
1 I PH Description
2 I PH Description
photo_df= df1.fillna('').filter(like='Photo')
photo_df = photo_df.fillna('')
product_df = df1.fillna('').filter(like='Description')
product_df = product_df.fillna('')
#assigned to vals1 for avoid overwrite `vals`vals1 = [(i, y) for i, x in enumerate(photo_df.to_numpy())
for y in vals[:3] + [['PH',z]
for z in photo_df.columns[x!='']]]
#removed vals[:4] for avoid duplicated rows vals2 = [(i, y) for i, x in enumerate(product_df.to_numpy())
for y in [['Descr',z]
for z in product_df.columns[x!='']]]
L = [df1.loc[df1.index[[i]], x].set_axis(range(len(x)), axis=1) for i, x in vals1]
#selected df1M = [df1.loc[df1.index[[i]], x].set_axis(range(len(x)), axis=1) for i, x in vals2]
df = pd.concat(L)
df3 = pd.concat(M)
#sorting index by mergesort (only stable algo)df = pd.concat([df,df3]).sort_index(kind='mergesort')
print (df)
0 1
0 I A
0 PH A1.jpg
0 PH A2.jpg
0 Description Nice
0 Description Beautiful
1 I B
1 PH B1.jpg
1 PH B2.jpg
1 PH B3.jpg
1 PH B4.jpg
1 Description Ugly
1 Description Damaged
2 I C
2 PH C1.jpg
2 Description Cute
2 Description Handsome
2 Description Nice
Solution 2:
You already have the merged/concatenated dataframe. Is it just a matter of getting the sorting right?
Try this:
df['sort'] = [len(x) for x in df[0]]
df['Item'] = df.index
df.sort_values(by=['Item', 'sort'], inplace=True)
df.drop(labels=['Item', 'sort'], axis=1, inplace=True)
print(df.to_string(header=False, index=False))
It produces this output:
IA
PH A1.jpg
PH A2.jpg
Description Nice
Description Beautiful
IB
PH B1.jpg
PH B2.jpg
PH B3.jpg
PH B4.jpg
Description Ugly
Description Damaged
I C
PH C1.jpg
Description Cute
Description Handsome
Description Nice
Post a Comment for "How To Fill The Values In The List And Convert It Into The Dataframe?(part Ii)"