在PANDAS中,层次结构中存在带有空格的数据。该列表示组中的一个类别,并且有一个空白单元格。
我想要填充空白,使用一个保持相同的值,直到下一个值到来。
例如
before
h10 h20 h30 h40
x AAA w1 x1
w2 xx
BBB w3 rx
rx
w5 2x
y CCC w6 rx
r4
t45
after
h10 h20 h30 h40
x AAA w1 x1
x AAA w2 xx
x BBB w3 rx
x BBB w3 rx
x BBB w5 2x
y CCC w6 rx
y CCC w6 r4
y CCC w6 t45import pandas as pd
df = pd.DataFrame({
'h10': ['x','',"","","",'y',"",''],
'h20': ["AAA","","BBB","","","CCC","",""],
'h30': ['w1','w2','w3','','w5',"w6","",""],
'h40': ['x1',"xx","rx","rx",'2x','rx','r4','t45']
})发布于 2020-10-29 20:50:59
你需要的是ffill (前向填充)。它将用该列中最后看到的值填充空白值。
df[‘h10’].fillna(method='ffill', inplace=True)或者,您可以尝试bfill (向后填充),如果它也出现的话。
发布于 2020-10-29 20:55:11
可以使用正则表达式将空字符串替换为nan值,然后使用ffill向前填充nan值。替换模式r'^$'表示字符串的开头紧跟字符串的结尾,这将与空字符串匹配。
import numpy as np
df.replace(r'^$', np.nan, regex=True).ffill()
# returns:
h10 h20 h30 h40
0 x AAA w1 x1
1 x AAA w2 xx
2 x BBB w3 rx
3 x BBB w3 rx
4 x BBB w5 2x
5 y CCC w6 rx
6 y CCC w6 r4
7 y CCC w6 t45https://stackoverflow.com/questions/64591187
复制相似问题