3

I have a dataframe that gets manipulated a few times. The end result is a data frame that looks like this:

    Company volume
1   NV      14
2   GD      8
3   AB      6

I covert this dataframe into json format like so:

formattedDF.to_json(orient='columns')

However, I get something like this:

'{"company":{"1":"NV","2":"GD","3":"AB"},"volume":{"1":14,"2":8,"3":6}}'

Which is very close to what I want, but the format I'm looking for is:

'{"company": ["NV", "GD","AB"], "volume":[14, 8, 6}]'

Where the keys give the values in array format instead. How can I achieve this?

2 Answers 2

5

Or:

print(df.to_dict(orient='list'))

Output:

{'Company': ['NV', 'GD', 'AB'], 'volume': [14, 8, 6]}
Sign up to request clarification or add additional context in comments.

Comments

2

Using a dictionary comprehension:

{k: df[k].tolist() for k in df}

Or using apply(list):

df.T.apply(list, 1).to_dict()

Both produce:

{'Company': ['NV', 'GD', 'AB'], 'volume': [14, 8, 6]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.