user1781482
user1781482

Reputation: 633

Dictionary data to CSV with Pandas in Python 3

I have the code below that turns a CSV with two columns into a dictionary:

import pandas as pd

df = pd.read_csv('file.csv', sep=',')
dct = df.groupby('group').ip.apply(lambda x: x.tolist()).to_dict()

print(dct)
{'A': ['192.168.1.1', '192.168.1.4'],
 'B': ['192.168.1.2', '192.168.1.5'],
 'C': ['192.168.1.3', '192.168.1.6']}

How would I go about doing the reverse of that? I would have this dictionary:

dct = {'A': ['192.168.1.1', '192.168.1.4'],
 'B': ['192.168.1.2', '192.168.1.5'],
 'C': ['192.168.1.3', '192.168.1.6']}

And want to turn it to CSV with two columns like this:

ip,group
192.168.1.1,A
192.168.1.2,B
192.168.1.3,C
192.168.1.4,A
192.168.1.5,B
192.168.1.6,C

User @cᴏʟᴅsᴘᴇᴇᴅ helped me for the first part and pandas is above my python skills at the moment. Thanks for any help!

Upvotes: 0

Views: 246

Answers (1)

cs95
cs95

Reputation: 403128

pd.DataFrame + melt.

df = pd.DataFrame(dct).melt(var_name='group', value_name='ip')
print(df)
  group           ip
0     A  192.168.1.1
1     A  192.168.1.4
2     B  192.168.1.2
3     B  192.168.1.5
4     C  192.168.1.3
5     C  192.168.1.6

Save to a CSV using df.to_csv:

df.to_csv('out.csv', sep=',', index=False)

Upvotes: 1

Related Questions