我正在尝试解析Excel文件。我有一个数据框中的文件,我希望标题行基于一个值(在这种情况下,标题开始于cell ==' Hour')
此外,我希望数据帧在行之前的行中结束=='所有固定期间'。我不能在小区==' 12:00 PM'因为每个Excel文件都有不同的结束时间值。
这就是我的数据框架:
df1 = pd.DataFrame(
[['Business Dates','3/15/2017'],
['Locations','ABC Location'],
['Breakfast',5073.35],
['Lunch',1489.45],
['PM',129.93],
['Hour','Net Sales'],
['6:00 AM',11.56],
['7:00 AM',142.36],
['8:00 AM',153.54],
['9:00 AM',200.34],
['10:00 AM',240.33],
['11:00 AM',110.12],
['12:00 PM',114.11],
['All Fixed Periods',]],
columns=['Service Performance Summary','Sales'])
df1
Service Performance Summary Sales
0 Business Dates 3/15/2017
1 Locations ABC Location
2 Breakfast 5073.35
3 Lunch 1489.45
4 PM Break 129.93
5 Hour Net Sales
6 6:00 AM 11.56
7 6:00 AM 150.34
8 7:00 AM 142.36
9 8:00 AM 153.54
10 9:00 AM 200.34
11 10:00 AM 240.33
12 11:00 AM 110.12
13 12:00 PM 114.11
14 All Fixed Periods None
成:
[['6:00 AM',11.56],
['7:00 AM',142.36],
['8:00 AM',153.54],
['9:00 AM',200.34],
['10:00 AM',240.33],
['11:00 AM',110.12],
['12:00 PM',114.11],],
columns=['Hour','Net Sales'])
Hour Net Sales
1 6:00 AM 11.56
2 6:00 AM 150.34
3 7:00 AM 142.36
4 8:00 AM 153.54
5 9:00 AM 200.34
6 10:00 AM 240.33
7 11:00 AM 110.12
8 12:00 PM 114.11
我最接近的是:
df.columns = df.iloc[5]
df = df[6:]
唯一的问题是"小时"可能会从不同报告的不同索引开始。
答案 0 :(得分:2)
我会使用vals = df1.values
col1 = vals[:, 0]
header_start = np.where(col1 == 'Hour')[0][0]
eodf = np.where(col1 == 'All Fixed Periods')[0][0]
pd.DataFrame(vals[header_start + 1:eodf], columns=vals[header_start])
Hour Net Sales
0 6:00 AM 11.56
1 7:00 AM 142.36
2 8:00 AM 153.54
3 9:00 AM 200.34
4 10:00 AM 240.33
5 11:00 AM 110.12
6 12:00 PM 114.11
找到第一个位置
argmax
还可以使用vals = df1.values
col1 = vals[:, 0]
header_start = (col1 == 'Hour').argmax()
eodf = (col1 == 'All Fixed Periods').argmax()
pd.DataFrame(vals[header_start + 1:eodf], columns=vals[header_start])
inc