当我将 Pandas 数据帧导出为 Stata.dta
格式时,加载此数据集后,任何布尔变量都将丢失:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': np.random.randn(100)})
df['positive'] = df['a'] > 0
df.to_stata('~/test.dta')
print(df['positive'].head())
test = pd.read_stata('~/test.dta', convert_categoricals=False)
print(test['positive'].head())
这个的输出是:
0 True
1 True
2 True
3 True
4 False
Name: positive, dtype: bool
0 1
1 1
2 1
3 1
4 0
Name: positive, dtype: int8
有没有办法保留系列的布尔类型?
您好在 to_stata 函数中使用 convert_strl 参数。这样做的用途是将列名列表转换为字符串列到Stata StrL 格式。仅当版本为 117 时可用。如果字符串超过 8 个字符且值重复,则以 StrL 格式存储字符串可以生成更小的 dta 文件。在 0.23.0 版本中。
df.to_stata('~/test.dta', version=117, convert_strl=[<the Column the you have the boolean valu>])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句