convert a dataframe into yaml file

Viewed 182

I am trying to make a yaml file from a dataframe with same entries in one column.

ID name
HN4 45_a
HN4 46_a
HN4 47_a

I tried this code, but doesnot work

df = pd.read_csv("input.txt",delimiter='\t')
df.set_index('ID', inplace = True)
df.columns = ["subject"]
dfdict = df.to_dict('list')

yaml.dump(dfdict)

The output I am looking for is

 subject:
         HN4: `
               45_a 
               45_a 
               45_a 
1 Answers

Use:

df = pd.read_csv('input.txt', delimiter='\t')
out = yaml.dump({'subject': df.groupby('ID')['name'].apply(list).to_dict()})
print(out)

# Output
subject:
  HN4:
  - 45_a
  - 46_a
  - 47_a
Related