从R转到Python,python等价于数据框架是什么?

scr*_*Owl 26 python r

我熟悉R数据持有者,如矢量,数据帧等,但需要进行一些文本分析,看起来python有一些很好的设置.我的问题是我在哪里可以找到python如何保存数据的解释.

具体来说,我在一个制表符分隔的文件中有一个数据集,其中文本在第3列,我需要的数据的评分在第4列.

id1            id2            text                             score
123            889     "This is the text I need to read..."      88
234            778     "This is the text I need to read..."      78
345            667     "This is the text I need to read..."      91
Run Code Online (Sandbox Code Playgroud)

在R中我只是将它加载到一个名为的数据框中df1,当我想调用一个列时,我会使用df1 $ text或者df1[,3] 如果我想要一个特定的单元格,我可以使用它df1[1,3].

我对如何将数据读入python而不是如何处理类似结构的表格有所了解.

你会如何建议为一个python新手使用它?

Jos*_*ich 31

查看pandas库中的DataFrame对象.


Bri*_*n B 14

Ullrich先生使用熊猫库的答案是最接近R数据框架的方法.但是,您可以使用numpy数组获得极其相似的功能,并在object必要时将数据类型设置为.较新版本的numpy具有类似于a的字段名称功能data.frame,其索引实际上比R更强大,并且它包含对象的能力远远超出了R的能力.

我使用R和numpy,具体取决于手头的任务.使用公式和内置统计数据更好.Python代码更易于维护,更容易与其他系统连接.

编辑:补充说明numpy现在具有字段名称功能


Bur*_*lid 8

我不确定这会转化为我从未使用过的'R',但在Python中,这就是我接近它的方式:

lines = list()
with open('data.txt','r') as f:
  for line in f:
      lines.append(line.split())
Run Code Online (Sandbox Code Playgroud)

这将读取python列表中的所有内容.列表从零开始.要从第二行获取文本列:

print lines[1][2]
Run Code Online (Sandbox Code Playgroud)

该行的得分:

print lines[1][3]
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 7

除了Panda的DataFrame,您还可以使用rpy2库(来自http://thread.gmane.org/gmane.comp.python.rpy/1344):

import array
import rpy2.robjects as ro

d = dict(x = array.array('i', [1,2]), y = array.array('i', [2,3]))
dataf = ro.r['data.frame'](**d)
Run Code Online (Sandbox Code Playgroud)


big*_*jim 5

我过去使用的一个选项是csv.DictReader,它允许您按名称引用行中的数据(每行变为a dict):

import csv
with open('data.txt') as f:
    reader = csv.DictReader(f, delimiter = '\t')
    for row in reader:
        print row
Run Code Online (Sandbox Code Playgroud)

输出:

{'text': 'This is the text I need to read...', 'score': '88', 'id2': '889', 'id1': '123'}
{'text': 'This is the text I need to read...', 'score': '78', 'id2': '778', 'id1': '234'}
{'text': 'This is the text I need to read...', 'score': '91', 'id2': '667', 'id1': '345'}
Run Code Online (Sandbox Code Playgroud)