首页 > 解决方案 > 用 Pandas 中每个组中的特定值替换整个列

问题描述

我想用该行开头的值替换Column1每个中Group的值Column1Column0Date and Time :

东风:

    Column0         Column1         Column2         Column3        Group 
1   Date and Time : 10/01/17,0900   NaN             NaN            A    * value to replace with
2   NaN             NaN             NaN             NaN            A
3   Name            NaN             NaN             NaN            A
                                    ...

1   NaN             NaN             02/06/17,1030   NaN            B
2   Date and Time : 02/06/17,1000   NaN             NaN            B    * value to replace with
3   Details         05/07/17,1330   NaN             NaN            B
4   NaN             01/08/17,1400   Date and Time : NaN            B
                                    ...

预期输出:

    Column0         Column1         Column2         Column3        Group 
1   Date and Time : 10/01/17,0900   NaN             NaN            A
2   NaN             10/01/17,0900   NaN             NaN            A
3   Name            10/01/17,0900   NaN             NaN            A
                                    ...

1   NaN             02/06/17,1000   02/06/17,1030   NaN            B
2   Date and Time : 02/06/17,1000   NaN             NaN            B
3   Details         02/06/17,1000   NaN             NaN            B
4   NaN             02/06/17,1000   Date and Time : NaN            B
                                    ...

标签: pythonpandasdataframe

解决方案


Series.str.startswith首先按条件选择行,通过选择和最后使用boolean indexing创建:SeriesGroupColumn1Series.map

s = (df[df['Column0'].str.startswith('Date and Time', na=False)]
       .set_index('Group')['Column1'])
df['Column1'] = df['Group'].map(s)

推荐阅读