Can't declare a python function in Rstudio/Rmarkdown

Viewed 373

I am trying to execute a python code in Rstudio (Rmarkdown) in a python chunk and I cannot declare a function while I am getting an error:

IndentationError: unexpected indent (, line 1)

(I am not mixing tabs with spaces or so)

The following code doesn't work in Rstudio's python chunk but works perfectly fine in Python Spyder IDE.

import pandas as pd

cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
        'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
df

def convert(brand_column):
  df[brand_column] = df[brand_column].str.replace('A', '')
  df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')


convert("Brand")
df
convert("Brand_2")
df

Screen: enter image description here

1 Answers

You are needing to specify where you python is located. I am on a mac so here is how I can to do it. Your indent error did not occur to me, so maybe double check your indents and spaces.

---
output: html_document
---

```{r}
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
use_python("/usr/local/bin/python3")
```

```{python}

import pandas as pd

cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
        'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
df

def convert(brand_column):
  df[brand_column] = df[brand_column].str.replace('A', '')
  df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')


convert("Brand")
df
convert("Brand_2")
df
```    

enter image description here

If you have windows, it might be similar to "C:\\Users\\username\\Anaconda3\\python.exe") or such

Related