我正在尝试将 Pandas 数据框导出到 Excel,其中所有列均为文本格式。默认情况下,pandas.to_excel() 函数让 Excel 决定数据类型。导出包含 [1,2,'w'] 的列会导致包含 1 和 2 的单元格为数字,包含 'w' 的单元格为文本。我希望该列中的所有行都是文本(即 ['1','2','w'])。
我能够通过使用 .astype(str) 将我需要的列分配为文本来解决问题。但是,如果数据很大,我担心会遇到性能问题。如果我理解正确, df[col] = df[col].astype(str) 会复制数据,这效率不高。
import pandas as pd
df = pd.DataFrame({'a':[1,2,'w'], 'b':['x','y','z']})
df['a'] = df['a'].astype(str)
df.to_excel(r'c:\tmp\test.xlsx')
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?
我搜索了好几次,但没有看到任何关于此的内容。如果之前已经回答过这个问题,请原谅我。这是我的第一篇文章,我很高兴参加这个很酷的论坛。
编辑:感谢我收到的评论,我看到Converting a series of ints to strings - Why is apply 比 astype 快得多?为我提供了 astype(str) 的其他选项。这真的很有用。我还想知道 astype(str) 是否效率低下,因为它复制了数据,但我现在发现它没有。
我已使用默认设置创建了 AWS EMR 集群和笔记本。
当我打开笔记本时,内核不会启动。我收到消息“工作区未附加到集群”。
线索
我查看了笔记本发生故障的集群创建的日志文件。
在日志文件中https://aws-logs-***.s3.amazonaws.com/elasticmapreduce/j-3SOK08VFSQDPO/node/i-04af0a3d2d6d96cac/daemons/emr-on-cluster-env/gateway.log.gz,我发现以下内容:
Jupyter Enterprise Gateway 2.1.0 is available at http://127.0.0.1:9547
User 'root' is not authorized to start kernel 'Python 3'. Ensure KERNEL_USERNAME is set to an appropriate value and retry the request.
User 'root' is not authorized to start kernel 'PySpark'. Ensure KERNEL_USERNAME is set to an appropriate value and retry the request.
Run Code Online (Sandbox Code Playgroud)
我如何让笔记本内核工作
根据 Stackoverflow 帖子Notebooks on …
当我opencv-python-headless在 Google Colab 中安装时,需要 15 分钟才能完成。
我的代码:
! pip install --upgrade pip
! pip install opencv-python-headless
Run Code Online (Sandbox Code Playgroud)
这是一个带有此代码的笔记本,它重现了问题:https : //colab.research.google.com/gist/mherzog01/38b6cf71942a443da072f09bc097387f/slow-install-of-opencv-python-headless.ipynb。
该过程最终完成,但我想减少安装时间。
我从`Building wheel for opencv-python (PEP 517) ... -` 中看到了关于编译 OpenCV 的讨论,这很可能就是这里发生的事情。但是,同样的 SO 帖子指出,如果您升级pip,它将使用预制轮子。
编辑:将 @intsco 的解决方法添加到 Google Colab