在 Pandas 数据框中使用数学库检查 NaN
Checking for NaN with math library in a Pandas Dataframe
如果我将值 'some value'
分配给数据框的一个索引,则该列的其他索引 return NaN
。稍后我想遍历数据帧索引并将值从 NaN
更改。我正在尝试检查 math.isnan()
,但它需要输入中的浮点数。我可以使用什么功能来执行此检查?
import pandas as pd
import math
BabyDataSet = [['Bob', 968], ['Jessica', 155], ['Mary', 77], ['John', 578], ['Mel', 973]]
df = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])
df.ix[1, 'MyValue'] = 'some value'
for index, Name in df.iterrows():
if math.isnan(df.ix[index, 'MyValue']):
df.ix[1, 'MyValue'] = 'some other value'
print df
期望的输出:
Names Births MyValue
0 Bob 968 some other value
1 Jessica 155 some value
2 Mary 77 some other value
3 John 578 some other value
4 Mel 973 some other value
只需使用pandas
自己的fillna():
df.fillna('some other value')
如果您只想更改特定列,您可以提供字典:
df.fillna({'col_name': 'some other value'})
您甚至可以将不同列中的 NaN 更改为不同的值:
df.fillna({'col_a': 'some other value', 'col_b': 'other value'})
如果我将值 'some value'
分配给数据框的一个索引,则该列的其他索引 return NaN
。稍后我想遍历数据帧索引并将值从 NaN
更改。我正在尝试检查 math.isnan()
,但它需要输入中的浮点数。我可以使用什么功能来执行此检查?
import pandas as pd
import math
BabyDataSet = [['Bob', 968], ['Jessica', 155], ['Mary', 77], ['John', 578], ['Mel', 973]]
df = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])
df.ix[1, 'MyValue'] = 'some value'
for index, Name in df.iterrows():
if math.isnan(df.ix[index, 'MyValue']):
df.ix[1, 'MyValue'] = 'some other value'
print df
期望的输出:
Names Births MyValue
0 Bob 968 some other value
1 Jessica 155 some value
2 Mary 77 some other value
3 John 578 some other value
4 Mel 973 some other value
只需使用pandas
自己的fillna():
df.fillna('some other value')
如果您只想更改特定列,您可以提供字典:
df.fillna({'col_name': 'some other value'})
您甚至可以将不同列中的 NaN 更改为不同的值:
df.fillna({'col_a': 'some other value', 'col_b': 'other value'})