1 回答

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
# 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
添加回答
舉報