python - 按字母顺序排序数据框的索引
问题描述
我正在从 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链接
解决方案
这将完成你的工作。
解释:
- 首先,我用元组转换了你的时间列,比如
[('.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
推荐阅读
- javascript - forEach 代码不起作用,但是两个不同的 forEach 函数中的相同代码可以,为什么?
- python - 如何在具有优先键的两个键上加入熊猫数据框?
- wordpress - 如何使用 Alexa 技能从 WordPress 制作的网站中获取内容?
- ajax - 如何检查ajax resonse是对象还是简单字符串
- c++ - 使用 std::reference_wrapper
在构造函数中处理 const T& - 合适吗? - html - 定位固定的元素而不将其从文档流中移除
- javascript - 用于生产和登台的不同样式表
- azure - 后端在其他服务器上时重定向 Azure Active Directory 应用程序注册的 URI
- rcpp - 在 R 中运行 rcpp created 函数时,如何知道代码中的哪一行导致错误?
- javascript - 是否有任何选项可以通过 php 表单提交获取 typeahead.js 值?