简体   繁体   English

SPSS文件(.sav)通过rpy导入pandas时如何保留标签?

[英]How to preserve Labels when SPSS file (.sav) imported into pandas via rpy?

I'm looking to work on a SPSS files (.sav) using pandas . 我正在寻找使用pandas SPSS文件(.sav)。 In the absence of the SPSS program, here's what a typical file looks like when converted to .csv: 在没有SPSS程序的情况下,这是转换为.csv时典型文件的样子:

在此输入图像描述

On investigation into what the first two rows signify (I don't know SPSS), it seems that the first row contains the Label s, while the second row contains the VarName s. 在调查前两行的含义(我不知道SPSS)时,似乎第一行包含Label s,而第二行包含VarName

在此输入图像描述

When I bring the file into pandas thus: 当我将文件带入熊猫时:

import pandas.rpy.common as com

def savtocsv(filename):
    w = com.robj.r('foreign::read.spss("%s", to.data.frame=TRUE)' % filename)
    w = com.convert_robj(w)
    return w

and then do a head(), the first row (Label) is missing: 然后执行head(),第一行(Label)丢失:

在此输入图像描述

How can labels be maintained? 如何维护标签?

Labels in a sav file are stored in variable.labels attribute of the returning object from the read.spss function. sav文件中的标签存储在read.spss函数的返回对象的variable.labels属性中。

You can get the variable labels with the following: 您可以使用以下内容获取变量标签:

import pandas.rpy.common as com

def get_labels(filename):
    w = com.robj.r('attr(foreign::read.spss("%s"), "variable.labels")' % filename)
    w = com.convert_robj(w)
    return w

If you want to set the labels as the column names of your dataframe: 如果要将标签设置为数据框的列名:

import pandas.rpy.common as com

def savtocsv(filename):
    w = com.robj.r('foreign::read.spss("%s", to.data.frame=TRUE)' % filename)
    cols = list(com.robj.r("attr")(w, "variable.labels"))
    w = com.convert_robj(w)
    w.columns = cols
    return w

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Python - Pandas 打开或将 SPSS (.sav) 文件转换为 CSV? - How to open or convert SPSS (.sav) file into CSV using Python - Pandas? 无法在 pandas 模块中使用 python 打开 spss 文件(.sav) - Can't open spss file(.sav) with python in pandas module pd.read_sav 和 pyreadstat 太慢了。 如果必须使用 SAV/SPSS 文件格式,如何为大数据加速 Pandas? - pd.read_sav and pyreadstat are so slow. how can i speed up pandas for big data if i have to use SAV/SPSS file format? 如何将熊猫数据框保存到 sav 文件中 - how to save a pandas dataframe into a sav file 如何阅读 Python 中的 SPSS aka (.sav) - How to read SPSS aka (.sav) in Python 如何从.sav文件中提取枚举标签和相应的数值? - How to extract enumerated labels and corresponding numerical values from a .sav file? 如何在从 Pandas 数据帧保存 SPSS 系统 (sav) 文件的同时将系统缺失值从 nan 重新编码到空白空间? - How to recode SYSTEM missing values from nan to empty space while saving SPSS system (sav) files from pandas dataframe? 使用 pyreadstat 读取内存中的 SPSS 文件(.sav 或 .zsav) - Reading an SPSS file (.sav or .zsav) inmemory using pyreadstat 将 spss 文件转换为 Pandas 时标题已更改 - Headers changed when converting spss file to pandas 在Python中从SPSS访问标签时如何处理特殊字符? - How to handle special characters when accessing labels from SPSS in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM