python - 用 Pandas 中每个组中的特定值替换整个列
问题描述
我想用该行开头的值替换Column1
每个中Group
的值Column1
Column0
Date 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
...
解决方案
Series.str.startswith
首先按条件选择行,通过选择和最后使用boolean indexing
创建:Series
Group
Column1
Series.map
s = (df[df['Column0'].str.startswith('Date and Time', na=False)]
.set_index('Group')['Column1'])
df['Column1'] = df['Group'].map(s)
推荐阅读
- c - 用于将十进制转换为任何基数(从 2 到 36)的 C 代码
- android - Flutter - remove space between items in ListView
- r - 如何在 RShiny 中将列名与 FluidRow 合并
- java - 从java知道远程IP已连接
- opendaylight - 使用 Opendaylight 的链路聚合控制协议
- spring - 涡轮机不适用于 spring boot 2.0.6 和 spring cloud Finchley.SR1
- pdf - 创建附加在一起的所有条形图的 pdf
- sql-server - 将实例分配给滚动但重置 10 秒的时间间隔
- android - Android Emulator:设置代理服务器时如何不代理 10.0.2.2?
- java - 不能在内部类中使用变量