PyCharm 变量资源管理器不显示带有空格的 pandas 列名称

我有这个.xlsx文件,可以使用以下方法成功读取:


pandas.read_excel(file_name, sheet_name="customers", index_col=0)

这对于大多数列都很有效,但也有一些列在字符之间有空格,例如“个人资料 url”中的列。此列只是缺失。


编辑:


这是重现该问题的一些代码:


import pandas as pd


def read_excel(file_name):

    df = pd.read_excel(file_name, sheet_name="customers", index_col=0)

    for entry in df.iterrows():

        print(entry)

    return df



read_excel("test_table.xlsx")

这是一个要使用的示例表:


ID,First,Last,Profile Url

1,foo,bar,www.google.com

2,fake,name,https://stackoverflow.com/

这是第一次迭代中的条目值。这样做我可以获取对象First和Last。


我希望也能看到个人资料网址。

https://img3.mukewang.com/651e79e00001e75307600725.jpg

通过准备这个示例,我了解到任何以小写形式编写的标头也将被忽略。



繁花如伊
浏览 107回答 1
1回答

慕桂英3389331

该行为与任何特定文件类型无关,对于列名称中带有空格的任何数据框都是如此,无论创建数据框的方法如何。解决方案是通过用另一个字符(例如 )替换空格来修复列'_'。小写列名不会预设相同的问题。我的猜测是列名中存在前导或尾随空格,可以使用以下命令将其删除.str.strip()import pandas as pddf = pd.DataFrame({'col_no_spaces': [1, 2, 3], 'col with spaces': ['a', 'b', 'c'], ' col_with_leading_trailing_ws ': [4, 5, 6]})# display(df)   col_no_spaces col with spaces   col_with_leading_trailing_ws 0              1               a                               41              2               b                               52              3               c                               6请注意带空格的列,不可用于View as Series# strip leading and trailing whitespace, and replace spaces in column names with _df.columns = df.columns.str.strip().str.replace('\s+', '_', regex=True)# display(df)   col_no_spaces col_with_spaces  col_with_leading_trailing_ws0              1               a                             41              2               b                             52              3               c                             6请注意,所有列现在均可用于View as Series
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python