pandas替换数据帧单元格值

时间:2015-12-08 19:00:14

标签: python pandas

我有一个数据框,其中一些单元格的字符串类似于“< 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

此代码提供与上述相同的错误。

3 个答案:

答案 0 :(得分:3)

您可以使用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转换为字符串,因为对于in,int / float将失败。

答案 1 :(得分:0)

你可以找到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

答案 2 :(得分:0)

我认为有一种更简单的方法。看看DataFrame.replace()

这是未经测试的,但你应该能够做你想做的事情:

df.replace(to_replace='.*<.*', value=0.0, regex=True)