![](/img/trans.png)
[英]Python - how to replace values greater and smaller than a particular value
[英]How to find values in certain DataFrame columns that are greater/smaller than a given maximum, and then replace them with the previous row's values?
數據框df具有列“ Datetime”和“ A”,“ B”,“ C”,其中包含一些溫度作為浮點值:
abctemps = {"Datetime": ["2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05"],
"A": [1.0,4.5,8.0,11.1,100.2],
"B": [-5.0,-18.1,-7.3,-5000.3,-21.5],
"C": [4,87,3.0,7,81]}
df = pd.DataFrame(abctemps)
df
Datetime A B C
0 2018-01-01 1.0 -5.0 4.0
1 2018-01-02 4.5 -18.1 87.0
2 2018-01-03 8.0 -7.3 3.0
3 2018-01-04 11.1 -5000.3 7.0
4 2018-01-05 100.2 -21.5 81.0
A,B和C列包含溫度,但是某些值顯然太大 (或太小) 而無法滿足要求 (100.2,-5000.3、87、81), 因此我想將它們替換為上一個 (如果先前不存在,則替換為下一個)是否存在?) 值在同一列中 。 因此,例如在A列中,100.2將替換為11.1。 或在B列中,-5000.3和-7.3。
所需的輸出如下所示:
Datetime A B C
0 2018-01-01 1.0 -5.0 4.0
1 2018-01-02 4.5 -18.1 4.0
2 2018-01-03 8.0 -7.3 3.0
3 2018-01-04 11.1 -7.3 7.0
4 2018-01-05 11.1 -21.5 7.0
我在想一個函數:
過濾器僅顯示給定列中的值大於例如40的行,
抓取該行的.loc
基於該.loc
,在同一列中獲取上一行的值
用前一行的值替換不良值
我將如何執行此操作,或者還有另一種更好的方法? .loc
對這個有好處嗎? 感謝您的任何幫助。
編輯:我能夠做一個做到這一點的功能:
def longtozero(col, length):
try:
df.loc[df[col].str.len() > length, col] = df.loc[df.loc[df[col].str.len() > length, col].index[0]-1, col]
df[col] = df[col].astype('float64')
except:
pass
然后使用該列和所需的最大長度來調用該函數,例如:
longtozero("A", 3)
您可以先檢測每列中的離群值。 這是一種方法:
m = df.loc[:,:'C'].apply(lambda x: np.abs(x-x.mean()) <= (x.std()), axis=0)
A B C
0 True True True
1 True True False
2 True True True
3 True False True
4 False True False
然后使用布爾值索引並同時使用ffill()
和bfill
來確保您填充所有缺失的值:
df.loc[:,:'C'] = df.loc[:,:'C'].where(m).ffill().bfill()
A B C Datetime
0 1.0 -5.0 4.0 2018-01-01
1 4.5 -18.1 4.0 2018-01-02
2 8.0 -7.3 3.0 2018-01-03
3 11.1 -7.3 7.0 2018-01-04
4 11.1 -21.5 7.0 2018-01-05
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.