[英]Correct way to sort a slice of a pandas dataframe
I'm new to Pandas, and constantly getting the infamous SettingWithCopyWarning.我是 Pandas 的新手,并且不断收到臭名昭著的 SettingWithCopyWarning。 If I have code like the following I get the warning:如果我有如下代码,我会收到警告:
import pandas as pd
import numpy as np
t1 = pd.DataFrame({'A':np.random.randn(8), 'B': np.random.randint(0,4,8)})
table = t1[t1['B'] < 3]
print(table)
table.sort(['B'], inplace=True)
print(table)
In this case, is it just warning me that the original data frame (ie, 't1') will not be sorted when I run the sort?在这种情况下,它是否只是警告我在运行排序时不会对原始数据框(即“t1”)进行排序?
Is there a more accepted way to perform this sort of operation (getting a slice of a data frame, and then applying functions on that slice)?是否有更可接受的方法来执行此类操作(获取数据帧的切片,然后在该切片上应用函数)?
Why not make a copy of the slice?为什么不制作切片的副本? Then you will not have the warning.那么您将不会收到警告。
a = table.copy()
You can read more in the answers to this post How to deal with SettingWithCopyWarning in Pandas?您可以在这篇文章的答案中阅读更多内容如何处理 Pandas 中的 SettingWithCopyWarning? . .
You can also avoid to use inplace
, in this case the copy will be made behind the scene for you.您也可以避免使用inplace
,在这种情况下,将在幕后为您制作副本。
t1 = pd.DataFrame({'A':np.random.randn(8), 'B': np.random.randint(0,4,8)})
table = t1[t1['B'] < 3]
table = table.sort(['B'])
print(table)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.