Python 在给定列中填充上面单元格中的值

Python 在给定列中填充上面单元格中的值,python,pandas,Python,Pandas,对于标记为“Category”的列,我想用上面的值填充单元格,请参见下图中的df编号2 以下是我尝试过但没有成功的方法: df[df['Category']==" "] = np.NaN df = df['Category'].fillna(method='ffill') col = ['Category'] df.loc[:,col] = df.loc[:,col].ffill() df.loc[:,['Category']] = df.loc[:,['Category']].ffill()

对于标记为“Category”的列,我想用上面的值填充单元格,请参见下图中的df编号2

以下是我尝试过但没有成功的方法:

df[df['Category']==" "] = np.NaN
df = df['Category'].fillna(method='ffill')
col = ['Category']
df.loc[:,col] = df.loc[:,col].ffill()
df.loc[:,['Category']] = df.loc[:,['Category']].ffill()
df = df.set_index(df.columns[0])
col = ['Category']
df.loc[:,col] = df.loc[:,col].ffill()
然后我想保留每行的第二个实例(如果有意义的话),请参见下图中的DF3


在@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')

我们可以使用转换为NaN,然后删除重复的:

df['Category']=df['Category'].mask(df['Category'].eq('')|df['Category'].isnull()).ffill()
您可以尝试:

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()
结果:

            engagement
category              
Base            152.00
Female            0.34
Male              0.64
Non-binary         NaN
Prefer-not        0.01

请复制并粘贴您的数据框,不要显示图像为什么行
17
仍在您的数据框中?
df['Category']=df['Category'].ffill()
?“如果有意义”并不是定义行删除规则的最佳方式。然后
df['Category']=df['Category'].mask(df['Category'].eq('')\df['Category'].isnull()).ffill()
问题是他有“”个值……因此我们需要在转换之前转换为NaN