将python字典写入CSV,但仅包含特定列

2024-10-01 07:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,其中有8列,我需要写到CSV,它的工作非常完美,但我只想我的字典的特定列转换成CSV。怎么做

{'data': [{'channel_id': 'UCqTFe5Dz3mpixUrLfMmY6dw', 'title': 'Manoyek', 'channel_img': 'https://yt3.ggpht.com/a-/AN66SAx-JBOt1_NI6nXTBL2R95kDBaR6Spy9i4_q-g=s240-mo-c-c0xffffffff-rj-k-no', 'desc': 'Jestem Adrian' , 'subscriberCount_gained': 587372, 'subscriberCount_lost': 0}]}

from pandas import DataFrame data = DataFrame.from_dict(diction) print(data) data_to_write = data[["channel_id", "channel_img", "desc"]]


Tags: csvfromhttpsiddataframeimgdata字典
2条回答
import pandas as pd

dictionary = {'data': [{'channel_id': 'UCqTFe5Dz3mpixUrLfMmY6dw', 'title': 'Manoyek', 'channel_img': 'https://yt3.ggpht.com/a-/AN66SAx-JBOt1_NI6nXTBL2R95kDBaR6Spy9i4_q-g=s240-mo-c-c0xffffffff-rj-k-no', 'desc': 'Jestem Adrian' , 'subscriberCount_gained': 587372, 'subscriberCount_lost': 0}]}

data = pd.DataFrame.from_dict(dictionary["data"])

data_to_write = data[["channel_id", "channel_img", "desc"]]
data_to_write.to_csv("filename.csv")

使用熊猫!你知道吗

import pandas as pd

pd.DataFrame(dictionary).to_csv('filename.csv')

相关问题 更多 >