【问题标题】:Copying values of other cells in Pandas DataFrame [duplicate]在 Pandas DataFrame 中复制其他单元格的值 [重复]
【发布时间】:2019-05-05 18:42:27
【问题描述】:

所以我想要完成的是,每次在我的数据框中,我都会找到缺少日期和前五列其余部分的行,复制其上方行的值。示例:

0| Date      | Name | Amount | Address
1| 12/04/2018| Pepe | $1.00  | Avenue 1
2| NaT       | NaN  |  NaN   |  NaN (In this line i need the values of the line above)
3| 1/04/2018 | Tito |  $3.00 |  Avenue 2

.

for file in files:
  fileName = os.path.splitext(file)[0]
  if fileName == 'xxxxxxx (copy)':
    df = pd.read_excel(file)
        for index, row in df.iterrows():
          if pd.isna(df['Date'] 'And the rest of the 5 columns'):
            #Copy the values of the line above it

【问题讨论】:

  • ffill 是你想要的吗?但你为什么要这个? ffill 到数据框会对您的 df 造成严重损害。它会简单地删除所有NaN,这可能是你不想做的。此外,在您的数据框中,如果您的所有行都是空的,为什么不能从您的 df 中删除这些记录,而不是创建一个副本? df.dropna(how='all')
  • 我需要这个,因为每一行都是我们支付的收据,所以我收到一个带有这些数据的 xlsx,我用 pandas 读取它,如果有一行包含前五个空列 (NaN) 是我们支付给同一客户或提供商的另一张收据。正如您在示例中看到的那样,希望这听起来很清楚。

标签: python pandas


【解决方案1】:

所以我解决了它,使用 ffill(forward fill) 方法,这里是代码:

for file in files:
  fileName = os.path.splitext(file)[0]
  if fileName == 'File1':
    df = pd.read_excel(file)
    new_df = df.fillna(method="ffill")
    writer = pd.ExcelWriter('File1.xlsx', engine='xlsxwriter')
    new_df.to_excel(writer, 'Sheet 1')
    writer.save()

【讨论】:

    【解决方案2】:

    使用ffill() 继续上一行。

    例子:

    # Given
    df = pd.DataFrame({'word':['Alpha', np.NaN, 'Charlie'],
                      'Percentage 1':[10, np.NaN, 0],
                      'Percentage 2': [5, np.NaN, 4]})
    df
        word    Percentage 1    Percentage 2
    0   Alpha   10.0             5.0
    1   NaN     NaN              NaN
    2   Charlie 0.0              4.0
    
    df = df.ffill()
    
       word     Percentage 1    Percentage 2
    0  Alpha    10.0            5.0
    1  Alpha    10.0            5.0
    2  Charlie  0.0             4.0
    

    【讨论】:

    • 我不明白 ffill() 如何用下面的值填充“NaN”值?
    猜你喜欢
    • 2017-11-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2016-08-20
    • 2015-08-07
    • 1970-01-01
    • 2016-02-07
    相关资源
    最近更新 更多