简体   繁体   English

Python, Pandas,删除以 \n 开头的列

[英]Python, Pandas, drop a column that starts with \n

I have the following problem and I do not know how to solve it.我有以下问题,我不知道如何解决。 I have columns that start with a line break in excel or may for some reason start with \n as provided in the example here.我的列以 excel 中的换行符开头,或者由于某种原因可能以此处示例中提供的\n开头。

在此处输入图像描述

How do I drop columns that start like that?如何删除以这样开头的列?

df_test = pd.read_excel(r'C:\...\test.xlsx')
df_test.drop("\nSomething")

Simply typing it out like that results in KeyError: "['\\nSomething'] not found in axis" .简单地输入它会导致KeyError: "['\\nSomething'] not found in axis"

Try this:尝试这个:

df_test.drop(r"\nSomething", axis=1)

The r stands for raw - it reads '\n' as '\\n' r代表raw - 它读取'\n''\\n'

From the docs :文档

Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R';字符串和字节文字都可以选择以字母“r”或“R”作为前缀; such strings are called raw strings and treat backslashes as literal characters此类字符串称为原始字符串,并将反斜杠视为文字字符

If you want to drop the column \nSomething you can try如果你想删除列\nSomething你可以试试

df_test.drop("\\nSomething", axis = 1)

You could try something like this:你可以尝试这样的事情:

for col in df:
    if col.startswith(r"\n"):
        df.drop(columns=[col], axis=1, inplace=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM