Vdoo
Vdoo

Reputation: 131

Map a column name with a list value from another column

My df:

  Column_Name                            Values
0           X                           [1,2,3]
1           Y                           [a,b,c]
2           Z  [20-09-2020,20-12-2202,1-1-2001]
3           W                     [0.1,0.2,0.3]

# df.dtypes

Values         object
column_name    object
dtype: object

How i can create a new dataframe that would look like this where each value of the Column name would be a new column, like this:

   X  Y           Z    W
0  1  a  20-09-2020  0.1
1  2  b  20-12-2202  0.2
2  3  c    1-1-2001  0.3

Note i have already transposed the table:

df_all = pd.read_sql_table('Test',engine)
df_test = pd.Series({c:df_all[c].unique() for c in df_all})
df = pd.DataFrame({'column_name': df_test.index,'Values':df_test.values})
df.reset_index(drop=True,inplace=True)

Upvotes: 1

Views: 52

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71707

Use Series.tolist and create a new dataframe having the data from column Values and index as Column_Name then use DataFrame.T:

df1 = pd.DataFrame(df['Values'].tolist(), index=df['Column_Name'].tolist()).T

Result:

print(df1)
   X  Y           Z    W
0  1  a  20-09-2020  0.1
1  2  b  20-12-2202  0.2
2  3  c    1-1-2001  0.3

Upvotes: 1

Related Questions