大佬教程收集整理的这篇文章主要介绍了如何根据先前在熊猫数据框中找到的值填写 nan 值?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下示例数据框(普通数据框有 1000 多行)
df = pd.DataFrame({'P1':['jaap','tim','pIEt','tim'],'P2':['pIEt','jaap','jaap'],'Count1':[2,3,np.nan,np.nan],'count2':[3,1,np.nan]})
print(df)
P1 P2 Count1 count2
0 jaap pIEt 2.0 3.0
1 tim jaap 3.0 1.0
2 pIEt jaap NaN NaN
3 tim pIEt NaN NaN
4 tim jaap NaN NaN
现在我想根据以下规则找到一种巧妙的方法来填充 NaN
值:
The @R_419_6889@s found in P1 and P2 have to be the same.
因此,在行号 2
中找到的 nan 值必须与行 0
中的值相同,因为名称也被交换,所以只需要交换值。 3
行中的 nan 值应保留为 nan,因为在任何先前行中都找不到 tim
和 pIEt
的组合。行 4
中的 nan 值必须与行 1
中的值相同。
所以想要的结果是:
P1 P2 Count1 count2
0 jaap pIEt 2.0 3.0
1 tim jaap 3.0 1.0
2 pIEt jaap 3.0 2.0
3 tim pIEt NaN NaN
4 tim jaap 3.0 1.0
这个问题很相似: Pandas fillna using groupby
只有将那篇文章中提出的解决方案应用于这篇文章中的问题,结果才会略有偏差:
df.groupby(['P1','P2'])[['Count1','count2']].apply(lambda x: x.fillna(method = 'ffill'))
print(df)
Count1 count2
P1 P2
0 jaap pIEt 2.0 3.0
1 tim jaap 3.0 1.0
2 pIEt jaap NaN NaN
3 tim pIEt NaN NaN
4 tim jaap 3.0 1.0
如您所见,第 jaap
行中的名称 pIEt
和 0
更改了第 2
行中的列,因此它不起作用。
想法是首先在 concat
中使用 rename
创建具有更改顺序的 DataFrame,删除具有缺失值和可能重复项的行,并通过 DataFrame.update
更改原始值:
d = {'P2':'P1','P1':'P2','Count1':'count2','count2':'Count1'}
df1 = (pd.concat([df,df.rename(columns=d)])
.dropna(subset=['Count1','count2'])
.drop_duplicates(['P1','P2']))
df = df.set_index(['P1','P2'])
df1 = df1.set_index(['P1','P2'])
df.update(df1)
df = df.reset_index()
print (df)
P1 P2 Count1 count2
0 jaap piet 2.0 3.0
1 tim jaap 3.0 1.0
2 piet jaap 3.0 2.0
3 tim piet NaN NaN
4 tim jaap 3.0 1.0
以上是大佬教程为你收集整理的如何根据先前在熊猫数据框中找到的值填写 nan 值?全部内容,希望文章能够帮你解决如何根据先前在熊猫数据框中找到的值填写 nan 值?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。