python读入数据字典,在Python 3中使用Pandas将数据字典到CSV

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!

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值