![](/img/trans.png)
[英]numeric data converted to decimal while writing SPSS pyreadstat using python
[英]pyreadstat read and write spss without data loss
要使用 pandas/pyreadstat 讀取 spss .sav 文件,請使用:
df, meta = pyreadstat.read_sav()
要編寫數據框,請使用:
pyreadstat.write_sav(df)
如何在不丟失任何元數據的情況下讀取、編輯和寫入 .sav 文件,例如標簽和其他可以在 spss 中更改的內容?
如果這不可能完全實現,那么以這種方式最接近不丟失數據的方法是什么?
函數 write_sav 有許多參數來設置不同的元數據,例如 column_labels、variable_value_labels 等。
使用 read_sav 時,除了數據幀 df(元數據對象元數據)之外,您還會在原始文件中找到許多這些元數據。 您可以編輯它們(或不編輯),然后將它們傳遞給 write_sav 不同的參數,以便設置元數據。
話雖如此,可能無法像在 SPSS 中那樣設置每條元數據,所以這是盡可能接近的。
請閱讀文檔以了解您對 write_sav 有哪些參數,以及您在讀取 read_sav 時獲得了哪些元數據。 該文檔還為您指出了 README 中的位置,它解釋了如何設置不同的元數據,因此 README 也是一個很好的信息來源。
談話很便宜,這是代碼。 :-)
# using pyreadstat
from pyreadstat import write_sav
class TempFile(type(pathlib.Path())): # type: ignore
def __exit__(self, exc_type, exc_val, exc_tb):
filepath = str(self.absolute())
try:
os.remove(filepath)
except OSError:
logger.exception('romve temporary file: %s failed!', filepath)
self._closed = True
class SpssTool:
@classmethod
def to_spss(cls, df: DataFrame, io: BytesIO, metadata: metadata_container, *, compress: bool = False):
"""Writes a pandas dataframe to a BytesIO object.
Parameters
----------
df : pandas.DataFrame
pandas data frame to write to sav or zsav
io : BytesIO
the buffer to save spss file
metadata: metadata_container
spss file meta data container
compress : bool
whether compress to zsav.
"""
df.columns = SpssTool.get_legal_column_names(df.columns.to_list())
with TempFile(f'/tmp/{uuid4().hex}.{"zsav" if compress else "sav"}') as fp:
write_sav(
df=df,
dst_path=fp,
column_labels=metadata.column_labels if metadata else None,
variable_value_labels=dict(metadata.variable_value_labels) if metadata else {},
variable_measure=metadata.variable_measure if metadata else None,
)
io.write(fp.read_bytes())
一些解釋:
SpssTool.get_legal_column_names
這個是必須的,因為spss文件對列名有限制,詳見官方文檔: https ://www.ibm.com/docs/en/spss-statistics/27.0.0?topic=view-variable-names
metadata_container
這是來自
from pyreadstat import metadata_container
。 包含有關數據集信息的容器,您可以在以下位置找到更多詳細信息: https ://ofajardo.github.io/pyreadstat_documentation/_build/html/index.html#metadata-object-description
這些也許是你需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.