Pandas(Python):用上一行值填充空单元格? [英] Pandas(Python) : Fill empty cells with with previous row value?

查看:1393
本文介绍了Pandas(Python):用上一行值填充空单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它们以数字开头,我想用上一行值填充空单元格.例如,我有

I want to fill empty cells with with previous row value if they start with number. For example, I have

    Text    Text    
    30      Text    Text    
            Text    Text    
            Text    Text    
    31      Text    Text
    Text    Text    
    31      Text    Text    
            Text    Text    
            Text    Text    
    32      Text    Text
    Text    Text    
            Text    Text    
            Text    Text    
            Text    Text    
            Text    Text

但是,我想拥有

Text    Text    
30      Text    Text    
30      Text    Text    
30      Text    Text    
31      Text    Text
Text    Text    
31      Text    Text    
31      Text    Text    
31      Text    Text    
32      Text    Text
Text    Text    
        Text    Text    
        Text    Text    
        Text    Text    
        Text    Text

我试图通过使用以下代码来达到此目的:

I tried to reach this by using this code:

data = pd.read_csv('DATA.csv',sep='\t', dtype=object, error_bad_lines=False)
data = data.fillna(method='ffill', inplace=True)
print(data)

但是它不起作用.

反正有这样做吗?

推荐答案

首先,将空单元格替换为NaN:

First, replace your empty cells with NaNs:

df[df[0]==""] = np.NaN

现在,使用ffill():

df.fillna(method='ffill')
#       0
#0  Text
#1    30
#2    30
#3    30
#4    31
#5  Text
#6    31
#7    31
#8    31
#9    32

这篇关于Pandas(Python):用上一行值填充空单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆