[英]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'
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.