[英]Replace column names with quotations with no quotations
I am trying to replace my column names that have quotations and simply remove the quotations but when I try this:我正在尝试替换带有引号的列名并简单地删除引号,但是当我尝试这样做时:
for x in df.columns:
x = x.replace('"', '')
print(x)
Nothing happens and the quotations are still there.什么都没有发生,报价仍然存在。
I would do something like this我会做这样的事情
cols = [column_name.replace('"','') for column_name in df.columns]
df.columns = cols
CODE代码
import pandas as pd
df=pd.DataFrame({"a":[1,2],'"b"':[3,4]})
print('BEFORE')
print(df)
cols = [column_name.replace('"','') for column_name in df.columns]
df.columns = cols
print('AFTER')
print(df)
OUTPUT OUTPUT
BEFORE
a "b"
0 1 3
1 2 4
AFTER
a b
0 1 3
1 2 4
you can remove it by writing the following code:您可以通过编写以下代码将其删除:
col=[]
for x in df.columns:
x = x.replace('"', '')
col.append(x)
df.columns=col
To know more about column renaming: Check this Renaming columns in pandas要了解有关列重命名的更多信息:检查此重命名 pandas 中的列
One canonical solution to this problem is using pandas str.replace
on the header directly (this is "vectorized"):此问题的一个规范解决方案是直接在 header 上使用 pandas str.replace
(这是“矢量化”):
df = pd.DataFrame({"a": [1, 2], '"b"': [3, 4]})
df.columns = df.columns.str.replace('"', '')
df
a b
0 1 3
1 2 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.