python - Python pandas 从另一行更新行 value

我有一个类似下面给出的 dataframe 。

C1 SIZE  M   COLOR
C1 PRIZE L   COLOR
C1 COLOR Nan BLUE
C2 SIZE  L   COLOR
C2 PRIZE S   COLOR
C2 COLOR Nan YELLOW

我正在寻找将其转换为下面给出的方法。

C1 SIZE  M   BLUE
C1 PRIZE L   BLUE
C1 COLOR Nan BLUE
C2 SIZE  L   YELLOW
C2 PRIZE S   YELLOW
C2 COLOR Nan YELLOW

有人可以帮忙吗?

回答1

这应该工作

df = pd.DataFrame({'Col1': ['C1', 'C1', 'C1', 'C2', 'C2', 'C2'],
                   'Col2': ['SIZE', 'PRIZE', 'COLOR', 'SIZE', 'PRIZE', 'COLOR'],
                   'Col3': ['M', 'L', 'Nan', 'L', 'S', 'Nan'],
                   'Col4': ['COLOR', 'COLOR', 'BLUE', 'COLOR', 'COLOR', 'YELLOW'],
                   'COLOR': ['BLUE', 'BLUE', 'BLUE', 'YELLOW', 'YELLOW', 'YELLOW']})
# mask the rows that have COLOR in Col4, then propagate the color values across groups
df['COLOR'] = df['Col4'].mask(lambda x: x=='COLOR').groupby(df['Col1']).transform('first')
print(df)
  Col1   Col2 Col3    Col4   COLOR
0   C1   SIZE    M   COLOR    BLUE
1   C1  PRIZE    L   COLOR    BLUE
2   C1  COLOR  Nan    BLUE    BLUE
3   C2   SIZE    L   COLOR  YELLOW
4   C2  PRIZE    S   COLOR  YELLOW
5   C2  COLOR  Nan  YELLOW  YELLOW

回答2

您可以尝试将 COLOR 替换为 NaN value 然后向前和向后替换 NaN value

df['d'] = df['d'].replace('COLOR', pd.NA)
df = df.groupby('a').apply(lambda g: g.bfill().ffill())
print(df)

    a      b    c       d
0  C1   SIZE    M    BLUE
1  C1  PRIZE    L    BLUE
2  C1  COLOR  Nan    BLUE
3  C2   SIZE    L  YELLOW
4  C2  PRIZE    S  YELLOW
5  C2  COLOR  Nan  YELLOW

如果最后一行存在有效颜色,也可以试试

df['d'] = df['d'].replace('COLOR', pd.NA)

df = df.groupby('a').bfill()

相似文章

随机推荐

最新文章