【问题标题】:Why DataFrame.sort_index retuns None?为什么 DataFrame.sort_index 会返回 None?
【发布时间】:2016-06-06 16:47:24
【问题描述】:

我尝试按索引对数据框进行排序,结果为 None。为什么会发生? 这是我的数据框http://screencast.com/t/zOEuR6Uu 我打电话给:

levelData.sort_index(inplace = True)

无(((

 levelData.info()
<class 'pandas.core.frame.DataFrame'>
Index: 525 entries, 1 to 99
Data columns (total 2 columns):
win       525 non-null int64
action    525 non-null int64
dtypes: int64(2)
memory usage: 12.3+ KB

【问题讨论】:

  • 我猜它会被排序......因为它正在改变原始对象(levelData),所以没有什么可以返回,你还没有一个简单的处理。
  • 试试levelData.sort_index(axis = 1, inplace = True)
  • @NickilMaveli 我试过了,但它不起作用
  • @Merlin 是的,你猜
  • @OleksandraK 和 levelData.head() 并用 head 编辑新表以显示您想要的排序。

标签: python sorting pandas dataframe


【解决方案1】:

DataFrame.sort_index 遵循Command-Query separation principle,它表示函数应该是命令或查询,但不能同时是两者。

  • 命令会做一些事情,例如修改调用者(例如 DataFrame)并且应该返回 None。 (在允许它的语言中,命令不应返回任何内容。但由于 Python 中的所有函数都返回某些内容,因此约定是返回 None。)
  • 查询计算并返回结果但不修改调用者

inplace=True 使sort_index 成为一个命令。该方法修改了调用DataFrame,符合Command-Query原则,返回None

inplace=False(默认)使sort_index成为一个查询。 因此,如果您希望 sort_index 返回 DataFrame,请删除 inplace=True


真正的"inplace" operations 就像list.sort 修改原始数据没有 使用辅助数据结构。从这个意义上说,没有任何 Pandas 操作是真正到位的。当使用inplace=True 时,首先在辅助数据结构(例如另一个DataFrame)中计算结果,然后将底层数据复制到原始DataFrame 的shell 中。所以

df.sort_level(inplace=True)

等价于

df = df.sort_level()

inplace=True的存在主要是因为历史的惯性。 Pandas 首席开发者Jeff Reback says

我的个人意见:我从不使用就地操作。语法更难阅读,也没有任何优势。

【讨论】:

  • 当我删除 inplace=True 数据框在 sort_index 之后没有改变
  • @OleksandraK:当然不是。在这种情况下,新的数据帧是从函数返回的
猜你喜欢
  • 1970-01-01
  • 2021-03-23
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多