从给定列中的上方单元格填充值

时间:2019-11-18 14:49:07

标签: python pandas

对于标记为“类别”(Category)的列,我想用上面的值用空格填充单元格,请参见下图的df 2号。

这是我尝试过的方法,但是没有用:

function simplestGetPropOrFalse(someTest: Partial<Test>, prop: keyof Test): boolean {
    return someTest[prop] ?? false;
}

然后我想保留每行的第二个实例(如果可以的话),请参见下图的df 3。

enter image description here

3 个答案:

答案 0 :(得分:1)

我们可以使用Series.mask转换为NaN,然后​​删除重复项:

df['Category']=df['Category'].mask(df['Category'].eq('')|df['Category'].isnull()).ffill()

答案 1 :(得分:0)

在@ansev的帮助下,我有了代码的有效版本:

#fill whitespaces in 'Category' with values from cell above
df['Category'] = df['Category'].mask(df['Category'].eq('')).ffill()

#drop duplicates in column 'Category' and keep last instance
df = df.drop_duplicates(subset=['Category'], keep='last')

答案 2 :(得分:0)

您可以尝试:

Sub drawControlsAsGrid()

    Dim cols As Integer = 20
    Dim rows As Integer = 30

    Dim w As Double = 26.5
    Dim h As Double = 25.4

    Dim basePanel As Panel = New Panel
    basePanel.BackColor = Color.Transparent
    Me.Controls.Add(basePanel)
    basePanel.Dock = DockStyle.Fill
    basePanel.Width = Me.Width
    basePanel.Height = Me.Height
    basePanel.Location = New Point(0, 0)


    For i As Integer = 0 To cols
        For j As Integer = 0 To rows
            Dim newPanel As Panel = New Panel
            newPanel.Width = w
            newPanel.Height = h
            newPanel.BorderStyle = BorderStyle.FixedSingle
            newPanel.BackColor = Color.Transparent
            newPanel.Cursor = Cursors.Hand
            newPanel.Location = New Point(j * w, i * h)
            AddHandler newPanel.Click, Sub(sender As Object, e As EventArgs)
                                           MsgBox("Location.X : " & CType(sender, Control).Location.X &
                                                  "Location.Y : " & CType(sender, Control).Location.Y)
                                       End Sub



            basePanel.Controls.Add(newPanel)
        Next
    Next


End Sub

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    drawControlsAsGrid()
   End Sub

结果:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    [['Base', 152],
     ['Male', 98], ['-', .64],
     ['Female', 52], ['-', .34],
     ['Non-binary', '-'], ['-', '-'],
     ['Prefer-not', 2], ['-', .01]],
    columns=('category', 'engagement')
)

df = df.replace('-', np.nan)
df['category'] = df['category'].ffill()