Pandas str.split给了我一个意想不到的语法错误



我正在尝试使用split函数仅将列值替换为两个'..之间的字符串部分。这是我使用的行:

df["Sample"] = df["Sample"].str.split(".").str[1]

我也尝试使用以下方法,但遇到了同样的问题:

df["Sample"] = df["Sample"].str.split(".",maxsplit=1)

当我运行代码时,我收到以下语法错误:

df = df.drop(["Sample", "percent", "Reads"], axis=1)
^
SyntaxError: invalid syntax

当我尝试在没有上述行的情况下运行代码时,语法错误出现在另一行并且以前起作用的行上,因此我认为问题与新行有关。

这是完整的代码

import pandas as pd 
import glob
file_list = glob.glob("file paths here")
for f in file_list:
df = []
outFile = f.replace('Eukaryota_phylum','relative_abundance') 
df = pd.read_csv(f, sep="t", header=None)
df.columns = ["Sample", "percent", "Reads", "Taxon_ID", "Phylum"]
df["Sample"] = df["Sample"].str.split(".").str[1]
df["Phylum"] = df["Phylum"].str.replace("Eukaryota;"," ")
df["Phylum"] = df["Phylum"].str.replace(";", " ")
df["Reads"] = df["Reads"].astype(float)
df["Percent_Reads"] = 100*df["Reads"]/df["Reads"].sum()
df = df.rename(columns={"Percent_Reads": "Percent_Reads_"+str(df["Sample"])
df = df.drop(["Sample", "percent", "Reads"], axis=1)
with open(outFile, "w") as f_out:
df.to_csv(f_out, sep="t", index=None, header=True)

在上面的行中df = df.drop(["Sample", "percent", "Reads"], axis=1)您缺少结束})

尝试:

df = df.rename(columns={"Percent_Reads": "Percent_Reads_"+str(df["Sample"])})

最新更新