Home > Net >  Create pandas dataframe from the combination of list and dictionary
Create pandas dataframe from the combination of list and dictionary

Time:01-12

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)

CodePudding user response:

col = ['c1_1', 'c1_2', 'c1_3', 'c1$1']
d = {4:'improvement needed',5:'very bad'}
col_name = []
val_code = []
val_lable = []
for i in col:
    for k,v in d.items():
        col_name.append(i)
        val_code.append(k)
        val_lable.append(v)
detail = {
    "final_col_name": col_name,
    "final_val_code": val_code,
    "final_val_lable": val_lable,
}
df = pd.DataFrame(detail)

CodePudding user response:

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
  •  Tags:  
  • Related