Python Dataframe 使用 pd.cut 范围列对数据框进行排序

huangapple go评论97阅读模式
英文:

Python Dataframe sort the dataframe using pd.cut range column

问题

我有一个大型数据框,并使用 pd.cut 创建了一个温度范围列。这是可以的。现在我想知道该最小范围在最小-最大范围列中的最小范围。这样,我可以使用此列对数据框进行排序。

我的代码:

  1. # 目标:按 'temp_range' 列对以下数据框进行排序
  2. # 列应按以下顺序排序:'-60-50', '-10-0', '0-10', '20-30'
  3. xdf = pd.DataFrame(data={'temp_range':['-10-0','20-30','-60-50','0-10']})
  4. xdf['Min. temp range'] = xdf['temp_range'].apply(lambda x: x[:3])
  5. xdf

目前的解决方案:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20-
  4. 2 -60-50 -60
  5. 3 0-10 0-1

期望的解决方案:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20
  4. 2 -60-50 -60
  5. 3 0-10 0

按照 Min. temp range 列对期望的解决方案进行排序:

  1. xdf.sort_values('Min. temp range')

排序后的结果:

  1. temp_range Min. temp range
  2. 2 -60-50 -60
  3. 0 -10-0 -10
  4. 3 0-10 0
  5. 1 20-30 20
英文:

I have a big dataframe and I created a temperature range column by using pd.cut. This is fine. Now I want to know the minimum range in that min-max range column. So, I can use this column to sort the dataframe

My code:

  1. # Goal: sort below dataframe by the 'temp_range' columns
  2. # The column should be sorted as '-60-50','-10-0','0-10','20-30'
  3. xdf = pd.DataFrame(data={'temp_range':['-10-0','20-30','-60-50','0-10']})
  4. xdf['Min. temp range']= xdf['temp_range'].apply(lambda x:x[:3])
  5. xdf

Present solution:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20-
  4. 2 -60-50 -60
  5. 3 0-10 0-1

Expected solution:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20
  4. 2 -60-50 -60
  5. 3 0-10 0

Sort this expected solution by the Min. temp range column

  1. xdf.sort_values('Min. temp range')
  2. temp_range Min. temp range
  3. 0 -60-50 -60
  4. 1 -10-0 -10
  5. 2 0-10 0
  6. 3 20-30 20

答案1

得分: 2

使用 str.extract 函数:

  1. xdf['Min. temp range'] = xdf['temp_range'].str.extract('^(-?\d+)')

输出:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20
  4. 2 -60-50 -60
  5. 3 0-10 0

正则表达式演示

如果您不需要该列而只想排序:

  1. xdf.sort_values(by='temp_range', key=lambda s: pd.to_numeric(s.str.extract('^(-?\d+)', expand=False)))

输出:

  1. temp_range
  2. 2 -60-50
  3. 0 -10-0
  4. 3 0-10
  5. 1 20-30
英文:

Use str.extract:

  1. xdf['Min. temp range'] = xdf['temp_range'].str.extract('^(-?\d+)')

Output:

  1. temp_range Min. temp range
  2. 0 -10-0 -10
  3. 1 20-30 20
  4. 2 -60-50 -60
  5. 3 0-10 0

regex demo

If you don't need the column and just want to sort:

  1. xdf.sort_values(by='temp_range', key=lambda s: pd.to_numeric(s.str.extract('^(-?\d+)', expand=False)))

Output:

  1. temp_range
  2. 2 -60-50
  3. 0 -10-0
  4. 3 0-10
  5. 1 20-30

huangapple
  • 本文由 发表于 2023年4月6日 23:07:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定