在Python 3中使用Pandas将数据字典到CSV [英] Dictionary data to CSV with Pandas in Python 3
本文介绍了在Python 3中使用Pandas将数据字典到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的代码将带有两列的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']}
并希望将其转换为CSV并有两列,如下所示:
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
用户@cᴏʟᴅsᴘᴇᴇᴅ在第一部分帮助了我,而熊猫此时此刻超越了我的python技能。谢谢您的帮助!
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
+ 融化
。
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
使用 df.to_csv
保存到CSV:
df.to_csv('out.csv', sep=',', index=False)
这篇关于在Python 3中使用Pandas将数据字典到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文