Python - Cbind前一行和下一行到当前行

时间:2018-05-29 22:35:58

标签: python pandas dataframe matrix

我有一个像这样的Pandas数据框:

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5, 6]}
df = pd.DataFrame(data=d)

看起来像:

  doc  sent col1 col2 col3
0   0    0    5   4    8
1   0    1    6   3    2
2   0    2    1   2    9
3   1    0    6   1    6
4   1    1    5   1    5

我想将上一行和下一行绑定到每一列,如下所示(在我的示例中考虑“doc”和“sent”列,这些列为在看到之前或之后没有任何内容可以出现的索引下文):

  doc  sent col1 col2 col3 p_col1 p_col2 p_col3 n_col1 n_col2 n_col3
0   0    0    5   4    8    0      0      0      6       3      2  
1   0    1    6   3    2    5      4      8      1       2      9
2   0    2    1   2    9    6      3      2      6       1      6
3   1    0    6   1    6    0      0      0      5       1      5
4   1    1    5   1    5    6      1      6      0       0      0

1 个答案:

答案 0 :(得分:0)

使用pd.DataFrame.shift获取上一行/下一行,pd.concat合并数据帧& fillna将空值设置为零

null的存在将upts upcast为float,因为numpy整数数组不能包含null值,在将null替换为0后将其强制转换为int。

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  $(document).ready(function(){
	console.log("init");
	$(".first").change(function(){
		console.log(this);
	});
	$(".second").change(()=>{
		console.log(this);
	});
  });
</script>
</head>
<body>
    <input type="text" class="first" />
    <input type="text" class="second" />
</body>
</html>

输出:

cs = ['col1', 'col2', 'col3']
g = df.groupby('doc')

pd.concat([
   df, 
   g[cs].shift(-1).add_prefix('n'), 
   g[cs].shift().add_prefix('p')
], axis=1).fillna(0).astype(int)
相关问题