将 Pandas 数据框保存为 CSV
Pandas 是一个建立在 NumPy 库之上的开源库。它允许用户快速分析、数据清理和有效地准备数据。 Pandas 速度快,为用户提供高性能和生产力。
您使用的大多数数据集都称为 DataFrames。 DataFrames 是带有行和列索引的二维标记数据结构,其中每个单元格用于存储任何类型的值。基本上,DataFrame 是基于 NumPy 数组的字典。
让我们看看如何使用to_csv()
方法将 Pandas DataFrame 保存为 CSV 文件。
示例 #1:将 csv 保存到工作目录。
# importing pandas as pd
import pandas as pd
# list of name, degree, score
nme = ["aparna", "pankaj", "sudhir", "Geeku"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr = [90, 40, 80, 98]
# dictionary of lists
dict = {'name': nme, 'degree': deg, 'score': scr}
df = pd.DataFrame(dict)
# saving the dataframe
df.to_csv('file1.csv')
输出:
示例 #2:保存没有headers和index的 CSV。
# importing pandas as pd
import pandas as pd
# list of name, degree, score
nme = ["aparna", "pankaj", "sudhir", "Geeku"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr = [90, 40, 80, 98]
# dictionary of lists
dict = {'name': nme, 'degree': deg, 'score': scr}
df = pd.DataFrame(dict)
# saving the dataframe
df.to_csv('file2.csv', header=False, index=False)
输出:
示例 #3:将 csv 文件保存到指定位置。
# importing pandas as pd
import pandas as pd
# list of name, degree, score
nme = ["aparna", "pankaj", "sudhir", "Geeku"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr = [90, 40, 80, 98]
# dictionary of lists
dict = {'name': nme, 'degree': deg, 'score': scr}
df = pd.DataFrame(dict)
# saving the dataframe
df.to_csv(r'C:\Users\Admin\Desktop\file3.csv', index=False)
输出:
示例 #4:使用制表符将 DataFrame 写入 CSV 文件。
import pandas as pd
import numpy as np
users = {'Name': ['Amit', 'Cody', 'Drew'],
'Age': [20,21,25]}
df = pd.DataFrame(users, columns=['Name','Age'])#create DataFrame
print("Original DataFrame:")
print(df)
print('Data from Users.csv:')
df.to_csv('Users.csv', sep='\t', index=False,header=True)
new_df = pd.read_csv('Users.csv')
print(new_df)
输出:
Original DataFrame:
Name Age
0 Amit 20
1 Cody 21
2 Drew 25
Data from Users.csv:
Name\tAge
0 Amit\t20
1 Cody\t21
2 Drew\t25