在Python中将.CSV文件转换为.DTA文件 [英] Convert .CSV files to .DTA files in Python

查看:711
本文介绍了在Python中将.CSV文件转换为.DTA文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻求通过Python自动将许多.CSV文件转换为.DTA文件的过程. .DTA文件是Stata Statistics语言处理的文件类型.

I'm looking to automate the process of converting many .CSV files into .DTA files via Python. .DTA files is the filetype that is handled by the Stata Statistics language.

但是,我无法找到一种方法来执行此操作.

I have not been able to find a way to go about doing this, however.

R语言具有 write(.dta)允许将R中的dataFrame转换为.dta文件,并且通过RPy从Python有一个到R语言的端口,但是我不知道如何使用RPy来访问R中的write(.dta)函数.

The R language has write(.dta) which allows a dataFrame in R to be converted to a .dta file, and there is a port to the R language from Python via RPy, but I can't figure out how to use RPy to access the write(.dta) function in R.

有什么想法吗?

推荐答案

您需要Python的rpy2以及R中安装的foreign软件包.您可以通过启动R并键入install.packages("foreign")来实现.然后,您可以退出R并返回到Python.

You need rpy2 for Python and also the foreign package installed in R. You do that by starting R and typing install.packages("foreign"). You can then quit R and go back to Python.

然后这样:

import rpy2.robjects as robjects
robjects.r("require(foreign)")
robjects.r('x=read.csv("test.csv")')
robjects.r('write.dta(x,"test.dta")')

如果需要,您可以构造从Python变量传递给robjects.r的字符串,例如:

You can construct the string passed to robjects.r from Python variables if you want, something like:

robjects.r('x=read.csv("%s")' % fileName)

这篇关于在Python中将.CSV文件转换为.DTA文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆