根据标识符覆盖列中的NaN

时间:2018-03-21 10:56:35

标签: python pandas

我的数据框包含NaN - 列中的一些t - 值。 t - 列中的值属于某个id,每个id应该相同:

df = pd.DataFrame({"t"  :   [4, 4, 1, 1, float('nan'), 2, 2, 2, float('nan'), 10],
                   "id":    [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})

因此,我想覆盖NaNt的{​​{1}} NaN t id,最终结果为df = pd.DataFrame({"t" : [4, 4, 1, 1, 2, 2, 2, 2, 10, 10], "id": [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})

        For example i am displaying a home page after login.

        In the Home screen i have a menu in that menu i have options as  New Flight,Home.

        When i click on the home button i will load Home Screen only.
        For that i am using navctrl.push(HomePage). Every time user clicks that button
        it is adding the same page multiple time into the navigation stack.

        can you please tell me how to solve this problem.whenever user clicks the Home Button it want to remove the previous home page and newly it want to add the Home page.how can i achieve this?

2 个答案:

答案 0 :(得分:5)

新策略...通过删除na并使用loc和mask重新分配来创建地图。

import pandas as pd

df = pd.DataFrame({"t"  :   [4, 4, 1, 1, float('nan'), 2, 2, 2, float('nan'), 10],
                   "id":    [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})

# create mask
m = pd.isna(df['t'])

# create map
#d = df[~m].set_index('id')['t'].drop_duplicates()
d = df[~m].set_index('id')['t'].to_dict()

# assign map to the slice of the dataframe containing nan
df.loc[m,'t'] = df.loc[m,'id'].map(d)

print(df)

df返回:

   id     t
0   1   4.0
1   1   4.0
2   2   1.0
3   2   1.0
4   3   2.0
5   3   2.0
6   3   2.0
7   3   2.0
8   4  10.0
9   4  10.0

答案 1 :(得分:2)

sort_valuesgroupbytransform一起用于与first相同的列:

df['t'] = df.sort_values(['id','t']).groupby('id')['t'].transform('first')

替代解决方案是mapdropna drop_duplicates创建的Series

df['t'] = df['id'].map(df.dropna(subset=['t']).drop_duplicates('id').set_index('id')['t'])

print (df)
   id     t
0   1   4.0
1   1   4.0
2   2   1.0
3   2   1.0
4   3   2.0
5   3   2.0
6   3   2.0
7   3   2.0
8   4  10.0
9   4  10.0