我有一个数据帧,其中一些单元格有一个类似"<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: 0Working81_WinPython_32bit_2.7.5.3python-2.7.5libsite-packagesspyderlibwidgetsexternalshellsitecustomize.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
将单元格CCD_ 2转换为字符串,因为对于CCD_。
你可以用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.replacement().
这是未经测试的,但你应该能够用做你想做的事
df.replace(to_replace='.*<.*', value=0.0, regex=True)