Python/ Pandas : replacing certain values in multiple columns of large dataset

标签 python pandas replace dataframe nan

我有一个包含 320k 行和 450 列的小数据框。有一些带有列号的列表:

list1 = [1,3,5,...]
list2 = [4,9,...]
...

我的目标是替换当前列表中每列中的某些值,然后保存它:

df[df[list1] > 7] = np.nan
df[df[list2] >90] = np.nan
...

数据帧的大小让我分块进行:

for chunk in pd.read_csv(filePrev,chunksize=10000,header=None):
>>>  chunk[chunk[list1] >= 7] = np.nan
>>>  chunk[chunk[list2] >= 90] = np.nan
...
>>>  chunk.to_csv(newFile,mode='a',header=False,index=False)

但是有一个不正确的工作:我已经多次运行此代码,并且大多数情况下都无法完成工作(IPython 中的内存错误或刚刚被 Windows 关闭的应用程序),无论使用任何 chunksize 值。但是当它完成时,它在大多数字符串中将所有值替换为 NaN,并且有一些字符串全部被正确替换。

<小时/>

我在同一数据集的一小部分上尝试了相同的逻辑,它工作正常!

In [11]: df = pd.read_csv(filePrev,nrows=5,usecols=[1,2,3,4,5,6,7],header=None)

In [12]: df
Out[12]:
   1  2  3  4  5  6  7
0  1  1  1  1  1  1  1
1  3  1  1  1  2  1  1
2  3  1  1  1  1  1  1
3  3  1  1  1  2  1  2
4  3  1  1  1  1  1  1

In [13]: list = [1,7]

In [14]: df[df[list] > 1] = np.nan

In [15]: df
Out[15]:
    1  2  3  4  5  6   7
0   1  1  1  1  1  1   1
1 NaN  1  1  1  2  1   1
2 NaN  1  1  1  1  1   1
3 NaN  1  1  1  2  1 NaN
4 NaN  1  1  1  1  1   1

那么,对此有什么想法吗?我们可以以“分块”模式实现它,还是有其他方法(然后我需要一个例子)?我只是想将某些值替换为 NaN...:)

最佳答案

可以通过保持文件打开而不是每次都以附加模式打开文件来改进这一点:

with open(newFile, 'a') as f:
    for chunk in pd.read_csv(filePrev,chunksize=10000,header=None):
        chunk[chunk[list1] >= 7] = np.nan
        chunk[chunk[list2] >= 90] = np.nan
        chunk.to_csv(f, header=False, index=False)

最近有人在这里报告了此行为,此更改给了他们 a 98.3% performance gain在 Windows 上(我在 osx 上只看到大约 25%)。

<小时/>

如果您使用 Profile 或(ipython 的)%prun 运行 Python 代码,您可以看到调用时间最长的内容以及最多的函数调用。以question I was referring to above为例,大部分时间花在 python 的 close 函数上(每次调用 pd.read_csv 后都会关闭,除非您保持文件打开。)

<小时/>

注意:逻辑看起来不错,您没有分配给副本。正如您在较小的示例中看到的:代码有效!

关于Python/ Pandas : replacing certain values in multiple columns of large dataset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042938/

相关文章:

python - 使用 scapy 释放 DHCP

python - 资源已耗尽 Google Cloud Speech

python - 多个条件平均python

c# - 如何替换动态 JSON 中的属性值

ruby - 我可以使用字符串作为可执行代码行的一部分吗?

python - 与正在运行的 ubuntu python 服务器进程通信

python - Django断言post_save信号被调用

python - 有效地将 Pandas 数据框列的组合转换为键值对

python - Pandas 将时间序列从微秒降采样到分钟,并按分钟进行处理

javascript - 如何更改 rss 框中的每个网址?