【问题标题】:Replace some values in a dataframe with NaN's if the index of the row does not exist in a multi-index object如果多索引对象中不存在行的索引,则将数据框中的某些值替换为 NaN
【发布时间】:2019-04-01 07:42:02
【问题描述】:

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

    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 为第一个,这里是第一个数据框,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

我已尝试相应地更改代码,但它不起作用。有人可以看看这个吗?

【问题讨论】:

  • 这是一个警告,而不是错误:您的代码可能仍在执行您想要执行的操作。您究竟是如何创建和修改df1 的?可能有一条线,例如df1 = df1[boolean_mask]。将.copy() 添加到这样的行(将其转换为df1 = df1[boolean_mask].copy())可能会避免警告。
  • np.where 的预期输出是什么,因为您现在所做的操作没有意义。特别是因为您正在将数据帧索引与聚合索引进行比较。

标签: python pandas dataframe


【解决方案1】:

你需要用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

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2017-04-22
    • 2020-09-28
    • 2016-01-03
    • 1970-01-01
    • 2016-01-10
    • 2017-06-08
    • 2016-02-11
    • 2020-10-23
    相关资源
    最近更新 更多