我有一个这样的数据框
ID col1 col2
Abc 街 1 号 2017-07-27
1 无 2017-08-17
2018-07-15 Def 街 1 号
1 无 2018-08-13
月 fbg 街 2018-01-07
2 无 2018-08-12
2019-01-15 号 trf 街 2 号
我想过滤 col1 中的所有 “无”,并将相应的 col2 值添加到新的列 col3 中。我的输出是这样的
ID col1 col2 col3
1 Abc 街 2017-07-27 2017-08-17
1 Def 街 2018-07-15 2018-08-13
月 fbg 街 2018-01-07 2018-08-12
2019-01-15 号 trf 街 2 号
有人能帮我实现这个目标吗?
虽然不可否认的是明显的麻木
I,行 = pd。因子化 ([* zip (df.ID,df.col1.replace (“无”)
K,cols = pd。因子分解 (df.group by (i).cumcount ())
Dleft = pd.DataFrame (zip (['id' 、 'col1') 、 zip (* 行)
Drigt = pd.DataFrame (索引 = dleft.index,列 = np.arange (len (cols)) 2).add _ prefix ('col'
值 [i,k] = df.col2 值
Dleft.join (drigt)
ID col1 col2 col3
0 农行街 1 号 2017-07-27 2017-08-17
1 Def 街 2018-07-15 2018-08-13
2 2 fbg 街 2018-01-07 2018-08-12
3 trf 街 2 号 2019-01-15 南
我正在使用Cumcount
与合并
Df1 = df.loc [df.col1.ne (“无”),:].copy ()
Df2 = df.loc [df.col1.eq (“无”),:].copy ()
Df1 ['key'] = df1.group by ('id').cumcount ()
Df2 ['key'] = df2.group by ('id').cumcount ()
Df1.merge (df2.drop ('col1',1),on = ['id','key'],how = 'left')
出【 816 】:
ID col1 col2x _ y 键
0 1 abc 街 2017-07-27 0 2017-08-17
1 1 Defstreet 2018-07-15 1 2018-08-13
2 fbgstreet 2018-01-07 0 2018-08-12
3 trfstreet 2019-01-15 1 NaN
使用Ffill
数据透视表
。这是假设没有
遵循从数据中显示的适当值。
U = df.assign (col1 = df.col1.replace (“无”))
G = ['id','col1']
Idx = u.group by (g).cumcount ()
(U.assign (idx = idx)
。数据透视表 (索引 = g,列 = 'idx',值 = 'col2',aggfunc = 'first')
。Reset_index ())
Idx ID col1 0 1
0 农行街 1 号 2017-07-27 2017-08-17
1 Def 街 2018-07-15 2018-08-13
2 2 fbg 街 2018-01-07 2018-08-12
3 trf 街 2 号 2019-01-15 南
尝试:
过滤器 = df ['col1'].isna ()
S = df.loc [过滤器,'col2'].copy ()
Df = df 【 ~ 滤镜】
Df ['col3'] = s.值
编辑: 正如你提到的,你想要的过滤器是'None'
,不是没有
,然后:
过滤器 = df ['col1'].eq (“无”)
又一次尝试:
F = df ['col1'] = 'no'
C3 = df.loc [f].col2.reset _ index (drop = True)
Df = df [~ f]
Df2 = pd.concat ([df.reset_ index (drop = True),c3),轴 = 1,ignore_index = True)
Df2 列 = ['id' 、 'col1' 、 'col2' 、 'col3']
ID col1 col2 col3
0 农行街 1 号 2017-07-27 2017-08-17
1 Def 街 2018-07-15 2018-08-13
2 2 fbg 街 2018-01-07 2018-08-12
3 trf 街 2 号 2019-01-15 南