Search code examples
pythondictionaryexport-to-csv

Convert Pandas DataFrame to CSV but only export specific columns


I have a pandas dataframe which has 8 columns which I need to write to CSV, it`s working perfectly but I just want specific columns of my dataframeto be converted to csv. How to do that

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

Solution

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