我們有以下虛擬資料框,用于收集給定日期的警告計數(基于原因):
temp = pd.DataFrame(np.array([['2022-10-13','one',123],['2022-10-13','two',77123],
['2022-10-13','three',451], ['2022-10-13','three',77]]),
columns = ['date','reason','count'])
問題出在計數列
date reason count
0 2022-10-13 one 123
1 2022-10-13 two 77123
2 2022-10-13 three 451
3 2022-10-13 three 77
原因一和三的資料需要縮放 100,因為它以最小化的方式存盤在資料庫中。
有沒有辦法遍歷單元格并將“00”添加到計數或乘以 100,其中原因不等于 2?最后得到這樣的結果:
date reason count
0 2022-10-13 one 12300
1 2022-10-13 two 77123
2 2022-10-13 three 45100
3 2022-10-13 three 7700
這將如何實作?
uj5u.com熱心網友回復:
首先確保列count是整數(或浮點數),然后使用.loc[]并選擇您希望調整的行(temp.reason != 'two')并進行更改(temp['count'] * 100):
temp['count'] = temp['count'].astype(int)
temp.loc[temp.reason != 'two', 'count'] = temp['count'] * 100
print(temp)
輸出
date reason count
0 2022-10-13 one 12300
1 2022-10-13 two 77123
2 2022-10-13 three 45100
3 2022-10-13 three 7700
uj5u.com熱心網友回復:
如果不匹配,則使用DataFrame.locwith*=100表示多個值Series.ne:
temp['count'] = temp['count'].astype(int)
temp.loc[temp['reason'].ne('two'), 'count'] *= 100
print (temp)
date reason count
0 2022-10-13 one 12300
1 2022-10-13 two 77123
2 2022-10-13 three 45100
3 2022-10-13 three 7700
uj5u.com熱心網友回復:
您可以使用np.where
temp['count'] = temp['count'].astype(int)
temp['count'] = np.where(temp['reason']!='two', temp['count']*100, temp['count'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518090.html
標籤:Python熊猫麻木的
下一篇:如何修改資料框
