data.csv(前兩列皆非資料):
import pandas as pd
# 读取数据文件,例如csv文件
df = pd.read_csv(‘data.csv’, header=[0, 1], sep=”,”)
# 印出DataFrame
print(df)
推薦hahow線上學習python: https://igrape.net/30afN
雙層column name的DF與
單層column name的DF合併
會變成單層column name的DF:
df_concat.columns = [‘_’.join(col).strip() for col in df_concat.columns.values]
#col 為tuple
取消第12列的註解
推薦hahow線上學習python: https://igrape.net/30afN
用pd.MultiIndex.from_arrays()
創建 雙層column name的DataFrame:
lis=[
[“a”,”b”],
[“c”,”d”],
[1,2],
[3,4],
[5,6],
[7,8]
]
import pandas as pd
df = pd.DataFrame(lis)
aryCol = df.iloc[0:2,:].values
“””
array([[‘a’, ‘b’],
[‘c’, ‘d’]], dtype=object)
“””
col = pd.MultiIndex.from_arrays(aryCol)
#pandas.core.indexes.multi.MultiIndex
df_data = df.drop([0,1])
df_data.columns = col
print(“df:\n”,df)
print(“\ndf_data:\n”,df_data)
輸出結果:
推薦hahow線上學習python: https://igrape.net/30afN