如何将Pandas DataFrame导出到CSV文件?

2021年9月19日22:43:40 发表评论 3,352 次浏览

Pandas DataFrame如何导出到CSV文件?你可以在 Python 中使用以下模板将Pandas DataFrame导出到CSV 文件

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)

如果你希望包含索引,只需从代码中删除“ , index = False ”:

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv')

接下来,你将看到一个完整的示例,其中:

  • 将从头开始创建一个 DataFrame
  • 然后,DataFrame 将导出为 CSV 文件

用于将Pandas DataFrame导出到CSV文件的示例

假设你有以下有关产品的数据:

ProductPrice
Desktop Computer850
Tablet200
Printer150
Laptop1300

你将如何在 Python 中为该数据创建一个 DataFrame?

(1) 首先,你需要安装Pandas 包(如果你还没有安装):

pip install pandas

(2) 然后,你就可以基于以下代码创建一个DataFrame:

import pandas as pd

data = {'Product': ['Desktop Computer','Tablet','Printer','Laptop'],
        'Price': [850,200,150,1300]
        }

df = pd.DataFrame(data, columns= ['Product', 'Price'])

print (df)

现在假设你要将刚刚创建的DataFrame导出到CSV 文件。

例如,让我们将 DataFrame 导出到以下路径:

r 'C:\Users\Ron\Desktop\ export_dataframe .csv '

请注意,路径的 3 个部分用不同的颜色突出显示:

  • 在黄色部分代表- [R字符,你应该把之前的路径名(在路径名中照顾任何符号,如反斜线符号)。否则,你将收到以下错误:  (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXXX escape
  • 在蓝色部分 表示要创建的文件名。如果你愿意,可以键入不同的文件名
  • 该绿色部分表示文件类型,这是“CSV”。你必须随时添加该部分要将 DataFrame 导出到CSV文件。或者,如果要将 DataFrame 导出为文本文件,则可以使用“txt”文件类型 

在运行下面的代码,你需要修改路径以反映的位置,你想的CSV文件存储在你的计算机。

这是完整的 Python 代码:

import pandas as pd

data = {'Product': ['Desktop Computer','Tablet','Printer','Laptop'],
        'Price': [850,200,150,1300]
        }

df = pd.DataFrame(data, columns= ['Product', 'Price'])

df.to_csv (r'C:\Users\Ron\Desktop\export_dataframe.csv', index = False, header=True)

print (df)

运行Python 代码后,CSV 文件将保存在你指定的位置。

请注意,如果你希望包含index,则只需从上面的代码中删除“ , index = False ”。

Pandas DataFrame导出到CSV文件:其他资源

Pandas DataFrame如何导出到CSV文件?你刚刚看到了创建 DataFrame 所需的步骤,然后将该DataFrame导出到CSV 文件。

你可能会遇到相反的情况,你需要将 CSV 导入 Python。如果是这种情况,你可以查看本教程,该教程解释了如何使用 Pandas将 CSV 文件导入 Python。

你可能还需要查看Pandas 文档以获取有关使用“to_csv”的更多信息。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: