Home > OS >  pandas: column name with ' separator
pandas: column name with ' separator

Time:01-21

Im reading a file which has a column with a ' in the column. Something like

df:

colA  col'21 colC 
abc   2001   Ab1

now I can't seem to read the column like:

df['col\'21']

It gives the KeyError.

CodePudding user response:

Your character is not a quote but the Right Single Quotation Mark

Replace this character by the standard quote:

df.columns = df.columns.str.replace('\u2019', "'")
print(df["col'21"])

To find the unicode character, use:

>>> hex(ord("’"))
'0x2019'

CodePudding user response:

You need to use the instead:

instead of:

df[YTD'21"]

try:

df["YTD’21"]

CodePudding user response:

I don't get any error:

df = pd.DataFrame({"col'21":[1,2,3]})

or

df = pd.DataFrame({"""col'21""":[1,2,3]})

Output:

   col'21
0       1
1       2
2       3
  • Related