首页 > 解决方案 > 将 Pandas DataFrame 转换为 CSV,但仅导出特定列

问题描述

我有一个熊猫数据框,它有 8 列需要写入 CSV,它工作得很好,但我只想将我的数据框的特定列转换为 csv。怎么做

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

{'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}]}

标签: pythondictionaryexport-to-csv

解决方案


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")

推荐阅读