python - pandas str.split给我一个意想不到的语法错误

标签 python pandas split syntax-error

我正在尝试仅用两个'之间的字符串部分替换列值。使用分割功能。这是我正在使用的行:

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"])})

关于python - pandas str.split给我一个意想不到的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62397062/

相关文章:

python-3.x - 如何管理Python中两个范围之间的值?

java - .contains() 和拆分字符串比较的优点?

ruby - 如何在 Ruby 中拆分字符串?

python - 渲染时捕获 NoReverseMatch,但具有匹配的 URL 名称

python - 使用图像处理检测近水平线

python - 如何在 python Popen 中将 args 传递给 args?

python - 具有 Python 相关信息的前五名表

python - Pandas :在没有行的地方添加零值(稀疏)

python - PyCharm 类型提示不适用于重载运算符

linux - shell 脚本 : to print selected text in the string