无法在Rstudio/Rmarkdown中声明Python函数

bxgwgixi  于 2024-01-03  发布在  Python
关注(0)|答案(1)|浏览(108)

我试图在Rstudio(Rmarkdown)中执行python代码,但我无法在收到错误时声明函数:
IndentationError: unexpected indent (<string>, line 1)
(我不会把制表符和空格之类的东西混在一起)
下面的代码在Rstudio的python chunk中不工作,但在Python Spyder IDE中工作得很好。

  1. import pandas as pd
  2. cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
  3. 'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
  4. }
  5. df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
  6. df
  7. def convert(brand_column):
  8. df[brand_column] = df[brand_column].str.replace('A', '')
  9. df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')
  10. convert("Brand")
  11. df
  12. convert("Brand_2")
  13. df

字符串
屏幕:

pbwdgjma

pbwdgjma1#

你需要指定你的python所在的位置。我在mac上,所以这里是我如何做到这一点。你的错误没有发生在我身上,所以也许仔细检查你的缩进和空格。

  1. ---
  2. output: html_document
  3. ---
  4. ```{r}
  5. library(reticulate)
  6. knitr::knit_engines$set(python = reticulate::eng_python)
  7. use_python("/usr/local/bin/python3")
  1. import pandas as pd
  2. cars = {'Brand': ['1HondaA','2ToyotaA','3FordA','4AudiA'],
  3. 'Brand_2': ['1HondaA','2ToyotaA','3FordA','4AudiA']
  4. }
  5. df = pd.DataFrame(cars, columns = ['Brand', 'Brand_2'])
  6. df
  7. def convert(brand_column):
  8. df[brand_column] = df[brand_column].str.replace('A', '')
  9. df[brand_column + "_number"] = df[brand_column].str.extract('(\d+)')
  10. convert("Brand")
  11. df
  12. convert("Brand_2")
  13. df
  1. 字符串
  2. ![](https://i.stack.imgur.com/mXD6V.png)
  3. 的数据
  4. 如果你有windows,它可能类似于`"C:\\Users\\username\\Anaconda3\\python.exe")`或类似的东西。
展开查看全部

相关问题