【问题标题】:Convert Pandas DataFrame to CSV but only export specific columns将 Pandas DataFrame 转换为 CSV,但仅导出特定列
【发布时间】:2018-11-16 13:15:40
【问题描述】:

我有一个 pandas 数据框,它有 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}]}

【问题讨论】:

标签: python dictionary export-to-csv


【解决方案1】:
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")

【讨论】:

  • 它说 KeyError 不在索引中
  • 请在您的问题中提供这一点,并请提供用词示例
  • 完成请检查
  • ...也是用词的例子:)
  • 我需要澄清你的字典的键。有没有 ["channel_id", "channel_img", "desc"]?
【解决方案2】:

使用熊猫!

import pandas as pd

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2017-03-17
    • 2017-03-23
    • 2017-11-14
    • 2015-08-08
    • 2019-11-28
    • 2018-10-09
    相关资源
    最近更新 更多