如果多索引对象中不存在行的索引,则用NaN替换数据框中的某些值

问题描述 投票:0回答:1

我有一个非常大的数据帧,类似于:

    Customer_Id   Day    Hour   Latitude   Longitude     
0.        a        dd     hh      x1         y1
1.        a        dd     hh'     x2         y2
2.        a        dd     hh'     x3         y3
3.        b        dd     hh'     x4         y4

然后我有一个对象(我可以在必要时将其转换为DataFrame),每个客户每小时每小时经纬度经过一次采样。但是,Customer_Id,Day和Hour都是这里的索引,而不是之前。它看起来像这样:

                                 Latitude   Longitude
Customer_Id    Day     Hour
    a          dd       hh         x1         y1
               dd       hh'        x3         y3
    b          dd       hh'        x4         y4

以前,我有两个数据帧,每个只有一个索引(让我们称之为df1为第一个,这里是firt数据帧,df2是第二个,这是我拥有的单个索引数据帧而不是第二个对象)所以我用过的:

df1['Latitude']= np.where((~df1.index.isin(df2.index)), np.nan, df1['Latitude'])

以前此代码有效,但现在在这种新方案下它返回此错误:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

我试图相应地更改代码,但它不起作用。有人可以看一下吗?

python pandas dataframe
1个回答
2
投票

您需要使用DataFrame.reset_index重置索引:

df1['Latitude']= np.where((~df1.index.isin(df2.reset_index().index)), np.nan, df1['Latitude'])

print(df1)
  Customer_Id Day Hour Latitude Longitude
0           a  dd   hh       x1        y1
1           a  dd  hh'       x2        y2
2           a  dd  hh'       x3        y3
3           b  dd  hh'      NaN        y4

reset_index有什么作用? 它将索引转换回列:

print(df2.reset_index())
  Customer_Id Day Hour Latitude Longitude
0           a  dd   hh       x1        y1
1           a  dd  hh'       x3        y3
2           b  dd  hh'       x4        y4
© www.soinside.com 2019 - 2024. All rights reserved.