如果所有值相等,如何替换整个Pandas数据帧行np.NaN公司

2024-09-20 22:52:24 发布

您现在位置:Python中文网/ 问答频道 /正文

示例代码和输出:

data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]} 

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]} 

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528

在第一个数据帧中,对于由ALL^{组成的每一行,我想用另一个数据帧中的一行来替换整行。在本例中,第二个数据帧的第0行,因此第一个df的结果与第二个数据帧的信息相同。在


Tags: 数据dfnewdatanancountrypopulationbrazil
3条回答

可以使用append组合它们,删除所有重复项(两个数据帧中的行),然后删除值为NaN的所有索引:

#combine into one data frame with unique values
df_country = df_country1.append(df_country2,ignore_index=True).drop_duplicates()

#filter out NaN rows
df_country = df_country.drop(df_country.index[df_country.isnull().all(axis=1)])

append中的ignore_index标志为每一行提供唯一的索引,这样当您搜索具有NaN行的索引并返回0时,您不会最终从df_country2中删除0索引行。在

我将连接两个数据帧:

data_complete=pd.merge(df_country1.dropna(),df_country2,on=['Country','Capital','Population'],how='outer')

您可以找到所有元素都有NaN的行,并使用以下方法将它们替换为其他数据帧的行:

# find the indices that are all NaN
na_indices = df_country1.index[df_country1.isnull().all(axis=1)]

# replace those indices with the values of the other dataframe
df_country1.loc[na_indices,:] = df_country2.loc[na_indices,:]

这假设数据帧的形状相同,并且您希望在缺少的行上进行匹配。在

相关问题 更多 >

    热门问题