[英]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.