更新数据框列中非NaN位置的值



我想更新数据框架列中非nan条目的值

import pandas as pd
from pprint import pprint
import numpy as np
d = {
't': [0, 1, 2, 0, 2, 0, 1],
'input': [2, 2, 2, 2, 2, 2, 4],
'type': ['A', 'A', 'A', 'B', 'B', 'B', 'A'],
'value': [0.1, 0.2, np.nan, np.nan, 2, 3, np.nan],
}
df = pd.DataFrame(d)

更新value列的数据在一个列表中

new_value = [10, 15, 1, 18]

我可以得到value

列中的非nan项
df["value"].notnull() 

我不确定如何分配新值。

建议会很有帮助。

df.loc[df["value"].notna(), 'value'] = new_value

通过df["value"].notna()选择value不是NAN的行,然后指定列(在本例中为值)。条件选择的行数必须与new_value中的值数匹配,这一点很重要。

您可以首先识别具有nan值的索引。

import pandas as pd
from pprint import pprint
import numpy as np
d = {
't': [0, 1, 2, 0, 2, 0, 1],
'input': [2, 2, 2, 2, 2, 2, 4],
'type': ['A', 'A', 'A', 'B', 'B', 'B', 'A'],
'value': [0.1, 0.2, np.nan, np.nan, 2, 3, np.nan],
}
df = pd.DataFrame(d)
print(df)
r, _ = np.where(df.isna())
new_value = [10, 15, 18] # There are only 3 nans
df.loc[r,'value'] = new_value
print(df)

输出:

t  input type  value
0  0      2    A    0.1
1  1      2    A    0.2
2  2      2    A   10.0
3  0      2    B   20.0
4  2      2    B    2.0
5  0      2    B    3.0
6  1      4    A   30.0

最新更新