Pandas DataFrame添加header使所有值变为NaN



我是Python新手。我几下就导入了excel文件。然后选择1,点击并尝试将分层列标题,但它生成的所有值NaN。然后,如果我改变输入从我的excel数据到Numpy数组它工作得很好。我不知道我哪里错了。

以下是代码。

fn= r'C:UsersYunNN_FXBbg_Today_Data.xlsx'
a=df_dict['Output'].iloc[:,[0,1,2,3]]
a.head(15)

输出
arrays = [["KRW","KRW", "MYR","MYR"],["Date", "Price","Date", "Price"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
bb=pd.DataFrame(a,columns=arrays)
bb.head(15)

输入图片描述

但是如果我尝试用Numpy数组。

arrays = [["KRW","KRW", "MYR","MYR"],["Date", "Price","Date", "Price"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
aa=np.random.randn(15, 4)
bb=pd.DataFrame(aa,columns=arrays)
bb.head(15)

输入图片描述

谁能告诉我哪里出错了?

通过columns属性设置列标签就足够了

import pandas as pd
fn = r'c:testBbg_Today_Data.xlsx'
df_dict = pd.read_excel(fn, sheet_name=None)
a = df_dict['Output'].iloc[:, [0, 1, 2, 3]]
a.columns = [["KRW", "KRW", "MYR", "MYR"], ["Date", "Price", "Date", "Price"]]
print(a.head(15))

输出:

KRW                               MYR           
Date        Price                 Date      Price
0   Updated at 09:13:39          NaN  Updated at 09:13:39        NaN
1              KRW=KFTC          NaN                 MYR=        NaN
2             Timestamp  Trade Close            Timestamp  Bid Close
3   2021-08-20 00:00:00       1179.6  2021-08-20 00:00:00      4.236
4   2021-08-19 00:00:00       1176.2  2021-08-19 00:00:00      4.237
5   2021-08-18 00:00:00         1168  2021-08-18 00:00:00      4.236
...

相关内容

  • 没有找到相关文章

最新更新