嗨,我有一个这样的 df,
Name sl no details score
0 Ram 1 ram is going to ooty NaN
1 Ram 2 ram sings well 1.5
2 Ravi 1 ravi play cricket 1.0
3 Ravi 2 ravi is in chennai NaN
4 Kumar 1 kumar passed the exam NaN
5 Kumar 2 kumar is in town NaN
6 Kumar 3 he left 3.0
我正在尝试移动分数列中的值。值应移动到 df[sl no]==1 或 df[Name] 是名称第一次出现的单元格
我的预期输出应该是这样的,
Name sl no details score
0 Ram 1 ram is going to ooty 1.5
1 Ram 2 ram sings well NaN
2 Ravi 1 ravi play cricket 1.0
3 Ravi 2 ravi is in chennai NaN
4 Kumar 1 kumar passed the exam 3.0
5 Kumar 2 kumar is in town NaN
6 Kumar 3 he left NaN
请帮忙。
请您参考如下方法:
next 列表解析
有条件地在列表理解内的迭代器上调用 next。
assert df['sl no'].eq(1).sum() == df['score'].notna().sum()
it = iter(df.score.dropna().tolist())
df['score'] = [
next(it) if i else np.nan for i in df['sl no'].eq(1)
]
df
Name sl no details score
0 Ram 1 ram is going to ooty 1.5
1 Ram 2 ram sings well NaN
2 Ravi 1 ravi play cricket 1.0
3 Ravi 2 ravi is in chennai NaN
4 Kumar 1 kumar passed the exam 3.0
5 Kumar 2 kumar is in town NaN
6 Kumar 3 he left NaN
如果您的 assert 语句失败,则说明您的数据有问题,您的要求不可行。
loc基于赋值
v = df.score.dropna().tolist()
df['score'] = np.nan
df.loc[df['sl no'].eq(1), 'score'] = v
df
Name sl no details score
0 Ram 1 ram is going to ooty 1.5
1 Ram 2 ram sings well NaN
2 Ravi 1 ravi play cricket 1.0
3 Ravi 2 ravi is in chennai NaN
4 Kumar 1 kumar passed the exam 3.0
5 Kumar 2 kumar is in town NaN
6 Kumar 3 he left NaN
