您收到错误,因为某些列不是元组,它们是索引中的字符串2368
to 2959
in df.columns
.
列是字符串的索引:
df.columns[2368:2959]
Index(['('z', '1', '1', '00h').1', '('z', '1', '1', '06h').1',
'('z', '1', '1', '12h').1', '('z', '1', '1', '18h').1',
'('z', '1', '2', '00h').1', '('z', '1', '2', '06h').1',
'('z', '1', '2', '12h').1', '('z', '1', '2', '18h').1',
'('z', '1', '3', '00h').1', '('z', '1', '3', '06h').1',
...
'('z', '1000', '2', '06h').1', '('z', '1000', '2', '12h').1',
'('z', '1000', '2', '18h').1', '('z', '1000', '3', '00h').1',
'('z', '1000', '3', '06h').1', '('z', '1000', '3', '12h').1',
'('z', '1000', '3', '18h').1', '('z', '1000', '4', '00h').1',
'('z', '1000', '4', '06h').1', '('z', '1000', '4', '12h').1'],
dtype='object', length=591)
由于您想要使用元组的多索引列数据框,因此我们首先通过使用必要的子字符串来清理这些字符串re.findall
with regex pattern = '(\(.*?\)).'
然后将该值传递给ast.literal_eval
用于自动将字符串转换为元组。最后,使用pd.MultiIndex.from_tuples
as:
df = pd.read_csv('teste.csv',index_col=[0,1,2,3,4],header=[0,1,2,3],parse_dates=True)
import re
import ast
column_list = []
for column in df.columns:
if isinstance(column,str):
column_list.append(ast.literal_eval(re.findall('(\(.*?\)).',column)[0]))
else:
column_list.append(column)
df.columns = pd.MultiIndex.from_tuples(column_list,
names=('variables', 'level','days','times'))
print(df.iloc[:,:6].head())
variables u
level 1
days 1 2
times 00h 06h 12h 18h 00h 06h
wsid lat lon start prcp_24
329 -43.969397 -19.883945 2007-03-18 10:00:00 72.0 0 0 0 0 0 0
2007-03-20 10:00:00 104.4 0 0 0 0 0 0
2007-10-18 23:00:00 92.8 0 0 0 0 0 0
2007-12-21 00:00:00 60.4 0 0 0 0 0 0
2008-01-19 18:00:00 53.0 0 0 0 0 0 0