【问题标题】:Special Sorting columns dataframes特殊排序列数据框
【发布时间】:2019-09-27 10:54:33
【问题描述】:

我有下面的数据帧。

 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)

【问题讨论】:

  • 如何获取计算列? .是你期望的输出吗?
  • 只是想要的输出
  • 您应该显示您的预期数据框......我们需要了解您的需求
  • @anky_91 我更新了我原来的帖子。请看一下
  • @Miss 当然,谢谢,你能解释一下你是如何得到第一行的 7 的吗?

标签: python-3.x pandas sorting dataframe


【解决方案1】:

在所有列中使用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

【讨论】:

  • @anky_91 - 我希望如此,如果t1 中的重复值然后按t2 排序(仅重复)和t3 相同,如果按所有列排序会得到什么。
  • 谢谢你。 @jezrael 你能解释一下你的解决方案吗?
  • @Miss - 就像排序值适用于更多列 - 首先按 t1 排序。 4 值有重复项,因此t2 的排序仅适用于具有4 的行。然后对于4 的组与t2 不重复,因此不按t3 排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 2014-11-20
  • 1970-01-01
相关资源
最近更新 更多