使用Pandas从Excel获取特定数据并将所有内容转换为字符串和NaN

问题描述 投票:0回答:1

我有一个Excel文件,第一行始终为空。第二行包含我不需要的数据。第三行始终是标题,随后的行始终是数据,其中TotalTitle_3Title_4下。

我使用pandas读取文件。我已经附上了结果的输出。

我的目标是,我希望数组中的所有内容都既是字符串又是nan。如何用字符串替换nan并显示如下输出:

目标输出

['nan', 'Title_1', 'RED_100', '2019-01-01 00:00:00', '10', 'nan']
['nan', 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', 'nan']
['nan', 'Title_3', 'RED_300', '2019-11-15 00:00:00', '30', 'Total']
['123456', 'Title_4', 'YELLOW_100', '2019-01-01 00:00:00', '40', '100']

代码

import pandas as pd
import io
import numpy as np

path = r'C:\Temp Files\Excel_2.xlsx'

df = pd.read_excel(path, dtype=str, index_col=None, na_values=['NA'])

#df.drop(df.head(2).index, inplace=True)

print(df)
res = (df.dropna(how='all') #remove completely empty rows
.dropna(how='all',axis=1) #remove completely empty columns
.T #flip columns into row position
#convert to list    
.to_numpy()
.tolist()
)

print()
Title_1 = res[1]
print(Title_1)

输出

            Unnamed: 0           Unnamed: 1           Unnamed: 2           Unnamed: 3
0                  NaN                  NaN                  NaN               123456
1              Title_1              Title_2              Title_3              Title_4
2              RED_100            GREEN_200              RED_300           YELLOW_100
3  2019-01-01 00:00:00  2018-02-02 00:00:00  2019-11-15 00:00:00  2019-01-01 00:00:00
4                   10                   20                   30                   40
5                  NaN                  NaN                Total                  100

[nan, 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', nan]

我的Excel文件

enter image description here

我需要的数据

enter image description here

python excel pandas numpy
1个回答
1
投票
© www.soinside.com 2019 - 2024. All rights reserved.