首页 > 解决方案 > 按字母顺序排序数据框的索引

问题描述

我正在从 csv 文件中读取数据帧,并且我正在尝试创建一个时间图,说明何时按出票频率来显示出票的时间。包含时间的列以小时格式设置,其中一个字母表示上午或下午,即 1200A。因此,当我尝试按升序对数据框进行排序时,只考虑数值,而忽略 A、P。如何对数据框的索引进行排序以考虑 A 和 P

我试过使用sort_index 函数,这有效,但只能对数字进行排序

from matplotlib 
import pyplot as plt 
import pandas as pd
tickets = pd.read_csv("./Parking_Violations_Issued_-_Fiscal_Year_2019.csv")

d2=tickets['Violation Time'].value_counts()
df2=d2.sort_index(ascending=1, sort_remaining='true')   

样本数据集:

Index  Violation Time
.847A   1
0000A   801
0000P   22
0001A   545
0001P   1
0002A   499
0003A   520
0004A   498
0004P   1
0005A   619
0006A   983
0007A   993
0008A   1034
0008P   1
0009A   1074

原始 CSV链接

标签: pythonpandascsvplotgraph

解决方案


这将完成你的工作。

解释:

  • 首先,我用元组转换了你的时间列,比如[('.847', 'A'), ('0000', 'A'), ('0001', 'A') ...
  • 接下来,我按照你的逻辑进行了排序,second element('A', 'P') of tuple and then first element(numbers)并加入了那些元组以恢复其原始状态。
  • 最后与原始数据集合并以获得所需的输出。

代码:

>>> tickets # Assuming your initial dataframe looks like below, as mentioned in OP
    Index  Violation Time
0   .847A          1  
1   0000A        801   
2   0000P         22   
3   0001A        545   
4   0001P          1   
5   0002A        499   
6   0003A        520   
7   0004A        498   
8   0004P          1   
9   0005A        619   
10  0006A        983   
11  0007A        993   
12  0008A       1034   
13  0008P          1   
>>> final_df = pd.DataFrame(["".join(i) for i in sorted(tickets.apply(lambda x: (x['Index'][:-1], x['Index'][-1]), axis=1), key=lambda x : (x[1], x[0]))])
>>> df2.rename(columns={0:'Index'}, inplace=True)

输出:

>>> final_df.merge(tickets)
    Index  Violation Time
0   .847A          1   
1   0000A        801   
2   0001A        545   
3   0002A        499   
4   0003A        520   
5   0004A        498  
6   0005A        619   
7   0006A        983   
8   0007A        993   
9   0008A       1034   
10  0009A       1074   
11  0000P         22   
12  0001P          1   
13  0004P          1   
14  0008P          1   

推荐阅读