Python 熊猫:如何使用包含np.nan的字符串列保存到hdf数据帧
我想知道当数据帧包含字符串列时,是否有一种好的方法将其保存到hdf 给定数据帧:Python 熊猫:如何使用包含np.nan的字符串列保存到hdf数据帧,python,pandas,hdf5,Python,Pandas,Hdf5,我想知道当数据帧包含字符串列时,是否有一种好的方法将其保存到hdf 给定数据帧: In [6]: df.head()
In [6]: df.head()
Out[6]:
Protocol Src Bytes
10 ICMP NaN 1062
11 ICMP 10.2.0.74 2146
12 ICMP 10.100.100.1 857520
13 ICMP 10.100.100.2 857520
14 ICMP 10.100.100.2 7000
df.to_hdf('save.h5','table')
结果:
/home/lpuggini/MyApps/python_2_7_numerical/lib/python2.7/site-packages/pandas/core/generic.py:1138: PerformanceWarning:
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->mixed,key->block0_values] [items->['Protocol', 'Src']]
return pytables.to_hdf(path_or_buf, key, self, **kwargs)
可以避免将列强制转换为str
,如下所示:
df['Src']=df['Src'].应用(str)
但是,np.nan
也将保存为'nan'
有没有更好的方法来保存包含
string
和np.nan
的列的数据帧?HDF文件中的列必须是单个数据类型nan
由numpy内部的float
表示。您可以通过以下方式将nan
值替换为空字符串:
df['src'].fillna('')
HDF在数字类型上的性能比字符串好得多,因此将IP地址转换为整数类型可能更有意义
编辑:参见下面的@Jeff注释。对于format='fixed',以上是正确的
Edit2:根据,可以为字符串dtype cols指定nan的磁盘上表示形式:
df.to_hdf((...), nan_rep='whatever you want')
除此之外,您还可以保存另一列或布尔值表,在检索字符串值时可以将其用作空字符串值的掩码;表格格式不支持对象数据类型(字符串)中的工厂值;这些转换为/从