使用基于列条件的值填充数据框列的值

时间:2016-01-09 05:41:44

标签: python pandas

如何通过比较列的值来填充数据框的列值。

Kpi_date cell_name call_Drop
2016-01-08  bgl_1238   0.3
2016-01-08  bgl_1233   0.7
2016-01-08  bgl_1245      
2016-01-08  bgl_1256   1.2

当值为空时,我想用{0}填充call_Drop列的值。

2 个答案:

答案 0 :(得分:1)

您可以先将call_Drop列中的所有值转换为数字to_numeric方法,然后将errors=coerce转换为NaN所有非数值,然后使用{{3 }}:

In [24]: df
Out[24]: 
     Kpi_date cell_name call_Drop
0  2016-01-08  bgl_1238       0.3
1  2016-01-08  bgl_1233       0.7
2  2016-01-08  bgl_1245          
3  2016-01-08  bgl_1256       1.2

df.call_Drop = pd.to_numeric(df.call_Drop).fillna(0)

In [26]: df
Out[26]: 
     Kpi_date cell_name  call_Drop
0  2016-01-08  bgl_1238        0.3
1  2016-01-08  bgl_1233        0.7
2  2016-01-08  bgl_1245        0.0
3  2016-01-08  bgl_1256        1.2

答案 1 :(得分:0)

您可以使用loc

print(vowelCount('its a death trap its a suicide rap'))
{'mostlyVowels': ['a', 'a', 'suicide'], 'halfVowels': [], 'mostlyConsonant': ['its', 'death', 'trap', 'its', 'rap']}

或条件不包含if %errorlevel2%==s ( echo. echo. echo Press any key to continue... echo. echo. pause>nul start haxmenu\pin.bat goto menu ) 的{​​{3}}:

df.loc[df['call_Drop'] == '' , 'call_Drop'] = 0
print df

     Kpi_date cell_name call_Drop
0  2016-01-08  bgl_1238       0.3
1  2016-01-08  bgl_1233       0.7
2  2016-01-08  bgl_1245         0
3  2016-01-08  bgl_1256       1.2

where

empty space

但也许价值不是df['call_Drop'] = df['call_Drop'].where(df['call_Drop'] != '', 0) print df Kpi_date cell_name call_Drop 0 2016-01-08 bgl_1238 0.3 1 2016-01-08 bgl_1233 0.7 2 2016-01-08 bgl_1245 0 3 2016-01-08 bgl_1256 1.2 而是print df Kpi_date cell_name call_Drop 0 2016-01-08 bgl_1238 0.3 1 2016-01-08 bgl_1233 0.7 2 2016-01-08 bgl_1245 3 2016-01-08 bgl_1256 1.2 df['call_Drop'] = df['call_Drop'].replace('', 0) print df Kpi_date cell_name call_Drop 0 2016-01-08 bgl_1238 0.3 1 2016-01-08 bgl_1233 0.7 2 2016-01-08 bgl_1245 0.0 3 2016-01-08 bgl_1256 1.2 ,然后条件更改为:

empty space

或者如果有space,则更多为:

df.loc[df['call_Drop'] == ' ' , 'call_Drop'] = 0