'Create pandas dataframe from the combination of list and dictionary

col = ['c1_1', 'c1_2', 'c1_3', 'c1$1']
d = {4:'improvement needed',5:'very bad'}

enter image description here

How to get the output like the above picture using pd.DataFrame (pandas library)



Solution 1:[1]

import pandas as pd

col = ['c1_1', 'c1_2', 'c1_3', 'c1$1']
# use list comprehension to duplicate each item in col list 
col = [col[i//2] for i in range(len(col)*2)]

d = {4:'improvement needed', 5:'very bad'}

df = pd.DataFrame({'final_col_name': col})
# duplicate each item in list of d keys
final_val_code = list(d.keys()) * int(df.shape[0] / 2) * int(df.shape[0] / 2)

df['final_val_code'] = final_val_code
# map d values to final_val_code col 
df['final_val_label'] = df['final_val_code'].map(d)

print(df) 

    final_col_name  final_val_code  final_val_label
0   c1_1            4               improvement needed
1   c1_1            5               very bad
2   c1_2            4               improvement needed
3   c1_2            5               very bad
4   c1_3            4               improvement needed
5   c1_3            5               very bad
6   c1$1            4               improvement needed
7   c1$1            5               very bad

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1