通常情况下,你可能想保存一个pandas DataFrame供以后使用,而不需要再从CSV文件中导入数据的麻烦。
最简单的方法是使用to_pickle()将DataFrame保存为一个pickle文件。
df.to_pickle("my_data.pkl")
这将在你当前的工作环境中保存DataFrame。
然后你可以使用read_pickle()来快速从pickle文件中读取DataFrame。
df = pd.read_pickle("my_data.pkl")
下面的例子展示了如何在实践中使用这些函数。
例子:保存和加载潘达斯数据框架
假设我们创建了下面这个包含各种篮球队信息的pandas DataFrame。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points': [18, 22, 19, 14, 14, 11, 20, 28],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
print(df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7 H 28 4 12
我们可以使用**df.info()**来查看DataFrame中每个变量的数据类型。
#view DataFrame info
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 team 8 non-null object
1 points 8 non-null int64
2 assists 8 non-null int64
3 rebounds 8 non-null int64
dtypes: int64(3), object(1)
memory usage: 292.0+ bytes
None
我们可以使用to_pickle()函数将这个DataFrame保存为一个扩展名为.pkl的pickle文件。
#save DataFrame to pickle file
df.to_pickle("my_data.pkl")
我们的DataFrame现在被保存为我们当前工作环境中的一个pickle文件。
然后我们可以使用**read_pickle()**函数来快速读取DataFrame。
#read DataFrame from pickle file
df= pd.read_pickle("my_data.pkl")
#view DataFrame
print(df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7 H 28 4 12
我们可以再次使用**df.info()**来确认每一列的数据类型与之前相同。
#view DataFrame info
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 team 8 non-null object
1 points 8 non-null int64
2 assists 8 non-null int64
3 rebounds 8 non-null int64
dtypes: int64(3), object(1)
memory usage: 292.0+ bytes
None
使用pickle文件的好处是,当我们保存和加载DataFrame时,每一列的数据类型会被保留。
这比保存和加载CSV文件有优势,因为我们不需要对DataFrame进行任何转换,因为pickle文件保留了DataFrame的原始状态。
其他资源
下面的教程解释了如何修复Python中的其他常见错误。
如何修复Pandas中的KeyError
如何修复。ValueError: 无法将浮点数NaN转换为整数
如何修复。ValueError:操作数不能与形状一起广播