python - 向后填充条件

标签 python pandas dataframe

我想在数据帧的特定列上应用向后填充,条件如下:我有“colum_A”只能假设四个值,称为 A、B、C、D,并且向后填充应该工作如下:

if the first not NaN is A, then backward_filling with A;

if the first not NaN is B, then backward_filling with B;

if the first not NaN is C, then backward_filling with B;

if the first not NaN is D, then backward_filling with C;

if the column_A only contains NaN, then backward_filling with D

例如:

输入DF:

colum_A
 NaN
 NaN
 B
 B
 C
 C

输出DF:

colum_A
 B
 B
 C
 C
 D
 D

拜托,任何帮助将不胜感激。 此致, 卡洛

最佳答案

我认为你需要map按条件使用bfill:

#get mask for back filling NaNs
m = df['colum_A'].isnull()
d = {'A':'A','B':'B','C':'B','D':'C'}
#D if all values NaN
df['colum_B'] = 'D' if m.all() else np.where(m, df['colum_A'].map(d).bfill(),df['colum_A'])
#alternative
#df['colum_B'] = 'D' if m.all() else df['colum_A'].mask(m, df['colum_A'].map(d).bfill())
print (df)
   colum_A colum_B
0      NaN       B
1      NaN       B
2        B       B
3        A       A
4      NaN       B
5        C       C
6        C       C
7      NaN       C
8      NaN       C
9      NaN       C
10       D       D
11       D       D
12       A       A
13       C       C
14     NaN       A
15       A       A
16     NaN     NaN

关于python - 向后填充条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46175104/

相关文章:

python - 单对象迭代器

Python情感分类

python - 无需合并的 Pandas 索引匹配

python - 在 JSON 序列化中嵌套一组带有新 header 的列

python - urllib2.urlopen 引发 urllib2.URLError

python - 如何在单个数据框中合并具有相同索引的行?

python - 用 Pandas 条形图上的值注释条形图

python - 无法进行矢量化时如何优化 pandas 数据帧的迭代

python - 如何在 python pandas 中获取唯一行值并返回 bool 结果?

python - 如何获取作为字典的数据帧的列的值