Python pandas str.split给了我一个意外的语法错误
我试图使用split函数仅用两个“.”之间包含的字符串部分替换列值。以下是我正在使用的行:Python pandas str.split给了我一个意外的语法错误,python,pandas,split,syntax-error,Python,Pandas,Split,Syntax Error,我试图使用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) ^ Sy
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上方的行中,您缺少结束}和
尝试:
你的语法错误是什么?AttributeError:'list'对象没有属性'str'?@Superdude`df=df.drop[Sample,percent,Reads],axis=1^SyntaxError:无效语法',并且错误从未出现在我认为导致我出现问题的行上。那么我如何在注释中以代码的形式显示?我是这个网站的新手,我觉得后面的勾号应该有用,但它没有出现?我编辑了原始帖子,将语法错误作为一个代码块包含进来。听起来你根据axelschmidt的答案修复了SyntaxError。请用更正后的代码和您现在收到的错误全文编辑您的帖子。你还应该包括一个小样本的数据。谢谢你,它一定已经被删除,但当我添加回来时,同样的问题仍然发生。
df = df.rename(columns={"Percent_Reads": "Percent_Reads_"+str(df["Sample"])})