亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PyCharm 變量資源管理器不顯示帶有空格的 pandas 列名稱

PyCharm 變量資源管理器不顯示帶有空格的 pandas 列名稱

繁花如伊 2023-10-05 16:54:02
我有這個.xlsx文件,可以使用以下方法成功讀?。簆andas.read_excel(file_name, sheet_name="customers", index_col=0)這對于大多數列都很有效,但也有一些列在字符之間有空格,例如“個人資料 url”中的列。此列只是缺失。編輯:這是重現該問題的一些代碼:import pandas as pddef read_excel(file_name):    df = pd.read_excel(file_name, sheet_name="customers", index_col=0)    for entry in df.iterrows():        print(entry)    return dfread_excel("test_table.xlsx")這是一個要使用的示例表:ID,First,Last,Profile Url1,foo,bar,www.google.com2,fake,name,https://stackoverflow.com/這是第一次迭代中的條目值。這樣做我可以獲取對象First和Last。我希望也能看到個人資料網址。通過準備這個示例,我了解到任何以小寫形式編寫的標頭也將被忽略。
查看完整描述

1 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

  • 該行為與任何特定文件類型無關,對于列名稱中帶有空格的任何數據框都是如此,無論創建數據框的方法如何。

  • 解決方案是通過用另一個字符(例如 )替換空格來修復列'_'。

  • 小寫列名不會預設相同的問題。我的猜測是列名中存在前導或尾隨空格,可以使用以下命令將其刪除.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

請注意帶空格的列,不可用于View as Series

https://img1.sycdn.imooc.com//651e79f800013c7708320399.jpg

# 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

請注意,所有列現在均可用于View as Series


查看完整回答
反對 回復 2023-10-05
  • 1 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號