python - 使用 Python 对 Excel 列进行排序

标签 python pandas sorting pivot

假设我有一个这样的列表:

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

到目前为止,我所做的只是对列进行基本排序:

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?

最佳答案

您可以使用 pandas.DataFrame.pivot()这样做:

代码:

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 - 使用 Python 对 Excel 列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982201/

相关文章:

python - 类型错误 : 'RangeIndex' object is not callable when trying to assign columns in pandas

php - 按输入字符串和位置自定义数组排序

Python - 从子包导入文件

python - 从解析的 ping 中存储值

python - Pandas tz_localize : Infer dst when localizing timezone in data with duplicates

python - 如何在wx.media中播放mp4文件

python - 从 for 循环值构建表

python - utf-8 编码在 pd.read_csv() 中给出错误

java - 对列表进行排序取决于另一个排序列表,该列表具有一个共同的排序属性

c - 如何在 C 中对结构体执行选择排序?