[英]pandas replace dataframe cell values
我有一個數據框,其中一些單元格有一個像“<0.5”的字符串。
我想迭代整個數據幀,對於任何包含小於號的單元格,我想用0.0替換整個單元格。
例如,<0.4變為0.0
編輯以添加一些代碼:
df = pd.read_csv(infl)
for i in range(df.shape[0]):
for j in range(df.shape[1]):
if "<" in df.ix[i,j]:
df.ix[i,j] = 0.0
這會產生錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\00Working\81_WinPython_32bit_2.7.5.3\python-2.7.5\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 538, in runfile
execfile(filename, namespace)
File "Z:/working/MINING/2015/01_read_data.py", line 24, in <module>
if "<" in df.ix[i,j]:
TypeError: argument of type 'numpy.int64' is not iterable
此代碼也不起作用:
df = pd.read_csv(infl)
for i in range(df.shape[0]):
for j in range(df.shape[1]):
if '<' in df.iloc[i][j]:
df[i,j] = 0.0
此代碼提供與上面相同的錯誤。
您可以使用applymap()
函數在所有單元格中執行特定項目,
In [92]: df
Out[92]:
a b
0 1 <.3
1 2 2
2 <.3 <.4
3 4 5
In [93]: df.applymap(lambda x: 0 if "<" in str(x) else x)
Out[93]:
a b
0 1 0
1 2 2
2 0 0
3 4 5
細胞轉化lambda x
為字符串因為INT /浮子將失敗in
。
你可以用str.contains
找到這些值,然后用你想要的東西填充它們(例如來自@WoodChopper):
In [12]: df
Out[12]:
a b
0 1 <.3
1 2 2
2 <.3 <.4
3 4 5
In [13]: df[df.apply(lambda x: x.str.contains('<'))] = 0
In [14]: df
Out[14]:
a b
0 1 0
1 2 2
2 0 0
3 4 5
我認為有一種更簡單的方法。 看看DataFrame.replace() 。
這是未經測試的,但您應該能夠做到您想要的:
df.replace(to_replace='.*<.*', value=0.0, regex=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.