![](/img/trans.png)
[英]Pandas Dataframe - Replace all cell value subject to regex condition
[英]How to replace all value in all columns in a Pandas dataframe with condition
我有以下數據框:
In [11]: import pandas as pd
In [12]: mydict = {'foo':[0, 0.3], 'bar':[1,0.55], 'qux': [0.3,4.1]}
In [13]: df = pd.DataFrame.from_dict(mydict, orient='index')
In [14]: df
Out[14]:
0 1
qux 0.3 4.10
foo 0.0 0.30
bar 1.0 0.55
我想要做的是用0替換所有小於1的值。產生:
0 1
qux 0 4.10
foo 0 0
bar 1.0 0
我怎樣才能做到這一點?
使用布爾索引並傳遞條件:
In [155]:
df[df<1] = 0
df
Out[155]:
0 1
bar 1 0.0
foo 0 0.0
qux 0 4.1
只是為了顯示這里發生的事情,執行df < 1
將返回一個布爾索引:
In [156]:
df < 1
Out[156]:
0 1
bar False True
foo True True
qux True False
然后我們將df
作為掩碼傳遞給df
,然后可以將新值分配為df[df<1]
請參閱文檔以獲取更多示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.