[英]Correct way to sort a slice of a pandas dataframe
我是 Pandas 的新手,并且不断收到臭名昭著的 SettingWithCopyWarning。 如果我有如下代码,我会收到警告:
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)
在这种情况下,它是否只是警告我在运行排序时不会对原始数据框(即“t1”)进行排序?
是否有更可接受的方法来执行此类操作(获取数据帧的切片,然后在该切片上应用函数)?
为什么不制作切片的副本? 那么您将不会收到警告。
a = table.copy()
您可以在这篇文章的答案中阅读更多内容如何处理 Pandas 中的 SettingWithCopyWarning? .
您也可以避免使用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.