【发布时间】:2021-11-05 01:52:47
【问题描述】:
如果有一个数据框,其中每个观测值都有一个标识观测值的 UniqueID 和一个标识对象的 ObjectID。同一个对象可以有多个观察值,即 ObjectID 不是唯一的。
一些观察值对变量具有 Null 值,但它仅取决于对象。因此,如果一个 ObjectID 出现多次并且至少指定了一次变量,则其他观察值的 Null 值应替换为该值。
我将 Python 与库 Pandas (pd) 和 Numpy (np) 一起使用
例子:
sample_frame = {'UniqueID': [1,2,3,4,5,6,7],"PersonID": [3,2,2,5,5,4,4], "Name":
["Alice",np.nan,"Bob","Joe","Joe",np.nan,np.nan]}
sample_frame = pd.DataFrame(data = sample_frame)
sample_frame
| Index | UniqueID | PersonID | Name |
|---|---|---|---|
| 0 | 1 | 3 | Alice |
| 1 | 2 | 2 | Bob |
| 2 | 3 | 2 | NaN |
| 3 | 4 | 5 | Joe |
| 4 | 5 | 5 | Joe |
| 5 | 6 | 4 | NaN |
| 6 | 7 | 4 | NaN |
因此,在索引为 2 的行中,Name 的 NaN 值应替换为“Bob”。 但是,下面的观察没有什么可做的。
我找到了一个可行的解决方案,但对我来说似乎有些复杂:
dup = sample_frame.loc[sample_frame.duplicated(subset = ["PersonID"]), :]
dup_persId = dup["PersonID"].unique()
name_na = sample_frame[sample_frame["Name"].isna()]
name_na_persId = name_na["PersonID"].unique()
dup_name_av = dup[dup["Name"].isna() == False]
dup_name_av_persId = dup_name_av["PersonID"].unique()
for i in name_na_persId:
if i in dup_name_av_persId:
index = sample_frame.index[sample_frame["PersonID"] == i].tolist()
for k in index:
if sample_frame.at[k,"Name"] is not np.nan:
name_temp = sample_frame.at[k,"Name"]
continue
for j in index:
if sample_frame.at[j,"Name"] is np.nan:
sample_frame.at[j,"Name"] = name_temp
else:
continue
有没有更简单的方法来做到这一点?
【问题讨论】:
-
想要的输出是什么?
标签: python pandas replace conditional-statements nan