python - 每隔一行更改一次值 - 熊猫
问题描述
我的目标是更改熊猫 df 中每隔一行的值。使用下面,我希望在Group
. 每组中的两行将Group
始终重复。但是,发生这种情况的方式是随机的。例如,我不会每隔一行将其更改为特定值。它改变的方法取决于上一行中的值。
具体来说,每组行将包含来自GR1
或的唯一值GR2
。我希望将第二个值更改为Group
第一个值不是的值。所以在下面使用,第一行将是A
或B
。因此,后续行将是相反的值。
注意: 的每个周期只有两个重复的行Time
。此外,内部的唯一值GR1
或GR2
将根据数据集的不同而有所不同,所以我希望能解释这一点。
df = pd.DataFrame({
'Time' : [1,1,2,2,3,3,4,4],
'GR1' : ['A','A','A','A','A','A','A','A'],
'GR2' : ['B','B','B','B','B','B','B','B'],
'Group' : ['A','A','B','B','B','B','A','A'],
})
GR1 = df['GR1'].unique()
GR2 = df['GR2'].unique()
groups = [y for x in [GR1, GR2] for y in x]
df['Group'] = np.where(df.index % 2, groups[0], groups[1])
东风:
Time GR1 GR2 Group
0 1 A B A
1 1 A B A # first row is from GR1 so this row is GR2
2 2 A B B
3 2 A B B # first row is from GR2 so this row is GR1
4 3 A B B
5 3 A B B # first row is from GR2 so this row is GR1
6 4 A B A
7 4 A B A # first row is from GR1 so this row is GR2
出去:
Time GR1 GR2 Group
0 1 A B B
1 1 A B A
2 2 A B B
3 2 A B A
4 3 A B B
5 3 A B A
6 4 A B B
7 4 A B A
预期输出:
Time GR1 GR2 Group
0 1 A B A
1 1 A B B
2 2 A B B
3 2 A B A
4 3 A B B
5 3 A B A
6 4 A B A
7 4 A B B
解决方案
这个想法是为最后三列中的每一列获取第二行,根据您的逻辑进行比较,然后用逻辑的结果替换原始数据框。
DT = df.copy()
DT.iloc[1::2, -1] = np.nan
# the second rows will be filled with the values from the previous row
DT = DT.ffill()
In [252]: gr1 = DT.iloc[1::2, 1]
In [253]: gr2 = DT.iloc[1::2, 2]
In [258]: check = DT.iloc[1::2, -1]
In [260]: bool1 = gr1==check
In [261]: bool2 = gr2==check
In [264]: condlist = [bool1, bool2]
In [265]: choicelist = [gr2, gr1]
In [267]: DT.iloc[1::2, -1] = np.select(condlist, choicelist)
In [268]: DT
Out[268]:
Time GR1 GR2 Group
0 1 A B A
1 1 A B B
2 2 A B B
3 2 A B A
4 3 A B B
5 3 A B A
6 4 A B A
7 4 A B B
推荐阅读
- c# - c# 中的表单切换与没有事件 form_load 的情况
- sql - 当列包含空值时,日期时间列的行为如何?
- php - 我希望我的子查询返回多个值(= 每个成员),这可能吗?
- python - 在同一类的另一个函数中获取函数的结果
- html - 浏览器同步未使用 gulp 连接项目中的 url 链接
- kotlin - 忽略声明性客户端 URI 参数的类型转换的属性
- ios - 尝试呈现视图控制器时对开始/结束外观转换的不平衡调用
- sql-server - 如何跟踪数据库上的所有数据更改
- sip - 当 SIP 代理无法到达端点时,状态代码 477 的适当 SIP 响应
- javascript - 如何将JSON(在订阅中)分配给角度变量