到目前为止,这是我的代码:
import numpy as np
import pandas as pd
df = pd.read_excel(r'file.xlsx', index_col=0)
我想将“未命名:*”列重命名为最后一个有效名称。
这是我尝试过的方法和结果:
df.columns = df.columns.str.replace('Unnamed.*', method='ffill')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-253-c868b8bff7c7> in <module>()
----> 1 df.columns = df.columns.str.replace('Unnamed.*', method='ffill')
TypeError: replace() got an unexpected keyword argument 'method'
如果我这样做,这“有效”
df.columns = df.columns.str.replace('Unnamed.*', '')
但是我有空白值或 NaN(如果我用 'NaN' 替换''。然后我尝试:
df.columns = df.columns.fillna('ffill')
这没有效果。所以我尝试了就地=真:
df.columns = df.columns.fillna('ffill', inplace=True)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-279-cce486472d5b> in <module>()
----> 1 df.columns = df.columns.fillna('ffill', inplace=True)
TypeError: fillna() got an unexpected keyword argument 'inplace'
然后我尝试了另一种方法:
i = 0
while i < len(df.columns):
if df.columns[i] == 'NaN':
df.columns[i] = df.columns[i-1]
print(df.columns[i])
i += 1
这给了我这个错误:
Oil
158 RGN Mistura
Access West Winter Blend
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-246-bc8fa6881b1a> in <module>()
2 while i < len(df.columns):
3 if df.columns[i] == 'NaN':
----> 4 df.columns[i] = df.columns[i-1]
5 print(df.columns[i])
6 i += 1
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
2048
2049 def __setitem__(self, key, value):
-> 2050 raise TypeError("Index does not support mutable operations")
2051
2052 def __getitem__(self, key):
TypeError: Index does not support mutable operations