使用 pd.read_stata() 作为 python pandas 数据框读取 stata .dta 文件

Reading in a stata .dta file as a python pandas data frame using pd.read_stata()

我想读入 .dta 文件作为 pandas 数据框。

我试过使用 https://www.fragilefamilieschallenge.org/using-dta-files-in-python/ 中的代码,但它给了我一个错误。

感谢您的帮助!

import pandas as pd
df_path = "https://zenodo.org/record/3635384/files/B-PROACT1V%20Year%204%20%26%206%20child%20BP%2C%20BMI%20and%20PA%20dataset.dta?download=1"
df = None
with open(df_path, "r") as f:
    df = pd.read_stata(f)
    print df.head()

open 可以在您的计算机上本地保存文件时使用。但是,对于 pd.read_stata,这不是必需的,因为您可以直接将文件路径指定为参数。

在这种情况下,您希望从 url 读取 .dta 文件,因此这不适用。不过解决方案很简单,因为 pd.read_stata 可以直接从 url 读取文件。

import pandas as pd
url = 'https://zenodo.org/record/3635384/files/B-PROACT1V%20Year%204%20%26%206%20child%20BP%2C%20BMI%20and%20PA%20dataset.dta?download=1'
df = pd.read_stata(url)