使用 Python 对 Excel 列进行排序 [英] Sorting Excel column with Python
本文介绍了使用 Python 对 Excel 列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的列表:
Let's say I have a list like this:
time type value
80 1A 10
100 1A 20
60 18 56
80 18 7
80 2A 10
100 2A 10
80 28 10
100 28 20
我需要把它改成这样:
time
type 60 80 100
1A 10 20
1B 56 7
2A 10 10
2B 10 20
到目前为止,我所做的只是对列进行基本排序:
So far what I did is just basic sorting of the column:
target_column = 0
book = open_workbook('result.xls')
sheet = book.sheets()[0]
data = [sheet.row_values(i) for i in range(sheet.nrows)]
labels = data[0]
data = data[1:]
data.sort(key= lambda x: x[target_column])
bk = xlwt.Workbook()
sheet = bk.add_sheet(sheet.name)
for idx, label in enumerate(labels):
sheet.write(0, idx, label)
for idx_r, row in enumerate(data):
for idx_c, value in enumerate(row):
sheet.write(idx_r+1, idx_c, value)
bk.save('resul.xls')
如何使用 Python 实现?
How can I it with Python?
推荐答案
您可以使用 pandas.DataFrame.pivot() 这样做:
You can use pandas.DataFrame.pivot() to do that like:
df.pivot(index='type', columns='time', values='value')
测试代码:
df = pd.read_fwf(StringIO(u"""
time type value
80 1A 10
100 1A 20
60 18 56
80 18 7
80 2A 10
100 2A 10
80 28 10
100 28 20"""), header=1)
print(df)
print(df.pivot(index='type', columns='time', values='value'))
结果:
time type value
0 80 1A 10
1 100 1A 20
2 60 18 56
3 80 18 7
4 80 2A 10
5 100 2A 10
6 80 28 10
7 100 28 20
time 60 80 100
type
18 56.0 7.0 NaN
1A NaN 10.0 20.0
28 NaN 10.0 20.0
2A NaN 10.0 10.0
这篇关于使用 Python 对 Excel 列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文