重新建立数据帧 [英] Reindexing dataframes

查看:88
本文介绍了重新建立数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框。然后我有一个逻辑条件,通过删除一些行,我创建另一个数据帧。然而,新的数据框会跳过已删除行的索引。如何顺利地重新索引而不跳过?以下是一个示例,以澄清

 将大熊猫导入pd 
导入numpy作为np

jjarray = np.array(range(5))
eq2 = jjarray == 2
neq2 = np.logical_not(eq2)

jjdf = pd.DataFrame(jjarray)
jjdfno2 = jjdf [neq2]

jjdfno2

Out: / p>

  0 
0 0
1 1
3 3
4 4

我希望它像这样:

  0 
0 0
1 1
2 3
3 4

谢谢。

解决方案

一种方法是使用 reset_index

 >>> df = pd.DataFrame(range(5))
>>> eq2 = df [0] == 2
>>> df_no_2 = df [〜eq2]
>>> df_no_2
0
0 0
1 1
3 3
4 4
>>> df_no_2.reset_index(drop = True)
0
0 0
1 1
2 3
3 4
pre>

I have a data frame. Then I have a logical condition using which I create another data frame by removing some rows. The new data frame however skips indices for removed rows. How can I get it to reindex sequentially without skipping? Here's a sample coded to clarify

import pandas as pd
import numpy as np

jjarray = np.array(range(5))
eq2 = jjarray == 2
neq2 = np.logical_not(eq2)

jjdf = pd.DataFrame(jjarray)
jjdfno2 = jjdf[neq2]

jjdfno2

Out:

  0
0 0
1 1
3 3
4 4

I want it to look like this:

  0
0 0
1 1
2 3
3 4

Thanks.

解决方案

One way is to use reset_index:

>>> df = pd.DataFrame(range(5))
>>> eq2 = df[0] == 2
>>> df_no_2 = df[~eq2]
>>> df_no_2
   0
0  0
1  1
3  3
4  4
>>> df_no_2.reset_index(drop=True)
   0
0  0
1  1
2  3
3  4

这篇关于重新建立数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆