python-3.x - 特殊排序列数据框
问题描述
我有下面的数据框。
d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4],
't3':[14,2,12,18,16,16,11]}
df = pd.DataFrame(data=d)
我想在 t1 上添加包含排序的列,然后如果两行的 t1 相等,那么我们可以查看 t2 并做同样的事情。我的专栏将包含。
df['calculated'] =[7,2,6,5,3,1,4]
我的预期数据框将是:
d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4],
't3':[14,2,12,18,16,16,11],'calculated':[7,2,6,5,3,1,4]}
df = pd.DataFrame(data=d)
解决方案
由所有列用于DataFrame.sort_values
测试是否相等并创建新列,例如DataFrame.assign
:
df1 = df.sort_values(['t1','t2','t3'], ascending=False).assign(new=range(1, len(df) + 1))
print (df1)
id t1 t2 t3 calculated new
5 x6 16 11 16 1 1
1 x2 11 14 2 2 2
4 x5 10 22 16 3 3
6 x7 8 4 11 4 4
3 x4 4 15 18 5 5
2 x3 4 4 12 6 6
0 x1 3 20 14 7 7
如有必要,最后添加原始索引DataFrame.sort_index
:
df1 = df1.sort_index()
print (df1)
id t1 t2 t3 calculated new
0 x1 3 20 14 7 7
1 x2 11 14 2 2 2
2 x3 4 4 12 6 6
3 x4 4 15 18 5 5
4 x5 10 22 16 3 3
5 x6 16 11 16 1 1
6 x7 8 4 11 4 4
推荐阅读
- python - python2中的理解列表工作正常,但python3中出现错误
- c# - 从通用 EditorFor 模板绑定模型属性的值
- google-apps-script - 如何使用带有脚本的 appendRow 将两行添加到谷歌工作表
- angular - 同一组件内的角度动画
- c++ - 类图中接口和类所需的关系,C++
- maven - maven中的传递依赖
- python - 合并具有不同和未知字段的数据帧
- linux - foreach 循环中的 TCSH 错误:files.list:找不到命令
- javascript - 如何将复杂的字符串拆分为数组?
- javascript - 如何通过过滤器在具有行跨度的表中进行搜索