在保存之前,我需要替换大DataFrame中的值(实际上,我在200 k行块中读取了1M+ SAS表,格式化数据并保存到castra存储中)。我使用Series.map(dict).combine_first(Series)替换值,而且速度很快。但是它不能用NaN替换值,因为combine_first返回旧的值。我尝试过使用replace方法,它工作了一段时间,最后给出了“无法比较类型对象和str”错误。
下面是一个相关的代码示例(200k int系列和12k项替换dict):
sl = pd.Series(range(200000))
r = {i: -i for i in range(100000,112000)}
sl2 = sl.map(r).combine_first(sl)
>> sl2[100001]
>> -100001.0
sl3 = sl.replace(r)
>> TypeError: Cannot compare types 'ndarray(dtype=int32)' and 'int'第一种方法以某种方式将int转换成浮点(这不是一个问题,因为我大部分都有字符串数据),第二种方法是在错误发生前占用8gb内存的20%。
那么,如何替换值并将一些值设置为NaN呢?
发布于 2016-01-05 16:39:36
我决定把这两种方法结合起来。首先是map非空值,然后是带有空值的replace。
def replace(s, d):
if type(d) is not pd.Series:
d = pd.Series(d)
dn = d[d.isnull()]
if len(dn):
d = d[~d.index.isin(dn.index)]
if len(d):
s = s.map(d).combine_first(s)
if len(dn):
s = s.replace(dn)
return shttps://stackoverflow.com/questions/34600429
复制相似问题