'Problems when calling Python from Stata 17
The first code below runs without problems in python, but when using the same lines in a Stata do-file, a message appears suggesting a Python coding error. Any idea what could cause this problem? (I am using Stata 17 on Windows.)
# PYTHON CODE:
import pandas as pd
df = pd.read_stata('data.dta')
cut_bins = [-5, -4, -3, -2, -1, 0, 1, 2, 3]
df['cut_bins'] = pd.cut(df['v'], bins=cut_bins)
* STATA CODE:
python
import pandas as pd
from sfi import Data
cut_bins = [-5, -4, -3, -2, -1, 0, 1, 2, 3]
df = Data.get('id bin v')
df["cut_bins"] = pd.cut(df['v'], bins=cut_bins)
end
When running the Stata code in a do-file, the following message appears:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
This suggests a Python coding error but since the identical lines run in Python without error, it may as well be that there is a problem with Stata.
Solution 1:[1]
df = Data.get('id bin v') will return the variables id, bin, and v in a list of lists. ie df[0] hold the first row of values of id, bin, and v.
Try this
* STATA CODE:
python
import pandas as pd
from sfi import Data
cut_bins = range(-5,4)
df = pd.DataFrame(Data.getAsDict('id bin v'))
df["cut_bins"] = pd.cut(df['v'], bins=cut_bins)
end
Now, df.head() would produce (using my fake data for id,bin and v):
id bin v cut_bins
0 1.0 1.0 2.535117 (2, 3]
1 2.0 2.0 0.161955 (0, 1]
2 3.0 3.0 -0.397220 (-1, 0]
3 4.0 4.0 0.003145 (0, 1]
4 5.0 5.0 -2.985772 (-3, -2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
