【问题标题】:Python Looping through a dataframe to find values associated with previous editions [duplicate]Python循环遍历数据框以查找与以前版本相关的值[重复]
【发布时间】:2019-11-30 18:35:04
【问题描述】:

我需要帮助编写一个循环来填充我丢失的数据。

假设我有一个这样的熊猫数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame([['A', '0', 'Apple', 2],
                   ['A', '1', '', 3],
                   ['B', '2', 'Grape', 2],
                   ['B', '3', 'Banana', 1],
                   ['B', '4', np.nan, np.nan],
                   ['B', '5', np.nan, np.nan]
                   ], columns = ['Index1', 'Index2', 'Value1', 'Value2'])

如果“ValueX”字段为空白或显示 nan,我想用与上一个条目关联的值填充该值,其中上一个条目被标识为 Index1 是相同的,Index2 是一个(或更多)小于当前。

例如,对于 Index1 = 'A' 和 Index2 = '1',我想填写 'Apple',因为这是与 A0 关联的值。
同样,我想用香蕉 1 填充 B4 用香蕉 1 填充 B5。

    Index1  Index2  Value1  Value2
0   A       0       Apple   2.0
1   A       1               3.0
2   B       2       Grape   2.0
3   B       3       Banana  1.0
4   B       4       NaN     NaN
5   B       5       NaN     NaN

将是:

        Index1  Index2  Value1  Value2
    0   A       0       Apple   2.0
    1   A       1       Apple   3.0
    2   B       2       Grape   2.0
    3   B       3       Banana  1.0
    4   B       4       Banana  1.0
    5   B       5       Banana  1.0

实际的数据集实际上有大约 20 个“值”字段,我可能想替换它们。

提前感谢您的帮助。

【问题讨论】:

  • df.mask(df.eq('')).groupby('Index1').ffill()

标签: python-3.x pandas


【解决方案1】:

IIUC,你想要的是:

df.replace('',np.nan).groupby('Index1').ffill()

输出:

  Index1 Index2  Value1  Value2
0      A      0   Apple     2.0
1      A      1   Apple     3.0
2      B      2   Grape     2.0
3      B      3  Banana     1.0
4      B      4  Banana     1.0
5      B      5  Banana     1.0

【讨论】:

  • 谢谢 - 这是否意味着我必须先按 Index1 和 Index2 的数据框排序才能得到正确的答案?由于代码似乎根本没有考虑 index2
  • 是的,您需要通过Index2 订购数据帧。 groupby 将照顾 Index1。此外,您没有填写Index1,因此无论如何对Index1 进行排序是无关紧要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 2021-02-26
  • 2022-08-17
  • 2018-10-16
  • 1970-01-01
  • 2019-08-07
  • 2021-10-04
相关资源
最近更新 更多