0

I want to get a file from the csv file formatted as follows: CSV file: CSV File Format CSV File Format

Desired output txt file (Header italicized):

MA Am1 Am2 Am3 Am4

MX1 X Y - -

MX2 9 10 11 12

Any suggestions on how to do this? Thank you!

Need help with writing the python code for achieving this. I've tried to loop through every row, but still struggling to find a way to write this.

1 Answers1

0

You can try this.

  1. Based on unique MA value groups, get the values [names column here]
  2. Create a new dataframe with it.
  3. Expand the values list to columns and add it to new dataframe.
  4. Copy name column from first data frame.
  5. Reorder 'name' column.

Code:

import pandas as pd
df = pd.DataFrame([['MX1', 1, 222],['MX1', 2, 222],['MX2', 4, 44],['MX2', 3, 222],['MX2', 5, 222]], columns=['name','values','etc'])

df_new = pd.DataFrame(columns = ['name', 'values'])
for group in df.groupby('name'):    
    df_new.loc[-1] = [group[0], group[1]['values'].to_list()]
    df_new.index = df_new.index + 1 
    df_new = df_new.sort_index() 

df_expanded = pd.DataFrame(df_new['values'].values.tolist()).add_prefix('Am')
df_expanded['name'] = df_new['name']

cols = df_expanded.columns.tolist()
cols = cols[-1:] + cols[:-1]
df_expanded = df_expanded[cols]

print(df_expanded.fillna('-'))

Output:

  name  Am0  Am1  Am2
0  MX2    4    3  5.0
1  MX1    1    2    -
Manjunath K Mayya
  • 1,078
  • 1
  • 11
  • 20