在Pandas DataFrame中复制其他单元格的值

时间:2018-12-04 10:49:02

标签: python pandas

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

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

2 个答案:

答案 0 :(得分:1)

使用thunk继续上一行。

示例:

ffill()

答案 1 :(得分:0)

所以我用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()