PyCharm变量资源管理器无法显示包含空格的pandas列名

3

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

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

这适用于大多数列,但对于像“profile 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/

这是第一次迭代中 entry 值的内容。 这样做,我可以获得 FirstLast 对象。

我希望也能看到 Profile Url

enter image description here

通过准备这个示例,我学到了任何小写字母编写的标题也将被忽略。

1个回答

1
  • 无论使用哪种方法创建数据框,只要列名中有空格,行为就与任何特定的文件类型无关。
  • 目前在JetBrains存在一个问题,涉及到这个行为。
  • 解决方法是通过用其他字符(例如'_')替换空格来修复列。
  • 小写列名不会出现同样的问题。我猜测列名中存在前导或尾随空格,可以使用.str.strip()去除。
import pandas as pd

df = 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                               4
1              2               b                               5
2              3               c                               6
  • 请注意,带有空格的列无法在“按系列查看”中使用。

enter image description here

# 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_ws
0              1               a                             4
1              2               b                             5
2              3               c                             6
  • 请注意,现在所有列都可以通过“按系列查看”进行查看。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接