everyone.
I need a help in creating the table with specified columns
Easy example:
from collections import defaultdict
import pandas as pd
d = defaultdict(list)
mapp = {'A': 'Error 3231', 'B': 'Error 23143243', 'C': 'Error 3242e32'}
for i in ['A', 'B']:
d[i].append(f'U1_{mapp[i]}')
for i in ['A', 'C']:
d[i].append(f'R1_{mapp[i]}')
When I use df1 = pd.DataFrame.from_dict(d, orient='index')
it creates
0 1
A U1_Error 3231 R1_Error 3231
B U1_Error 23143243 None
C R1_Error 3242e32 None
But actually, I want to get another table like the below one:
U1 R1
A U1_Error 3231 R1_Error 3231
B U1_Error 23143243 None
C None R1_Error 3242e32
The values U1 and R1 are fixed.
Thank you.
CodePudding user response:
Convert d
to create your dataframe. It is often preferable to reformat your data before creating your dataframe:
df = pd.Series({(k, v[:2]): v for k, l in d.items() for v in l}).unstack()
print(df)
# Output
R1 U1
A R1_Error dsad2314 U1_Error 232324
B NaN U1_Error 232324
C R1_Error dsad2314 NaN
Transformation:
# From
>>> dict(d)
{'A': ['U1_Error 232324', 'R1_Error dsad2314'],
'B': ['U1_Error 232324'],
'C': ['R1_Error dsad2314']}
# To
>>> {(k, v[:2]): v for k, l in d.items() for v in l}
{('A', 'U1'): 'U1_Error 232324',
('A', 'R1'): 'R1_Error dsad2314',
('B', 'U1'): 'U1_Error 232324',
('C', 'R1'): 'R1_Error dsad2314'}
CodePudding user response:
You can create the desired table by transposing the original dataframe and then renaming the columns. Here is an example:
df1 = pd.DataFrame.from_dict(d, orient='index')
df2 = df1.T
df2.columns = ['U1', 'R1']
This will transpose the original dataframe, which will make the columns into rows and vice versa. Then, you can rename the columns to 'U1' and 'R1'.