根据行编号删除数据帧的行

2024-04-25 22:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧(DF),还有一个如下的数组:

rm_indexes = np.array([1, 2, 3, 4, 34, 100, 154, 155, 199])

我想从DF中删除rm_indexes中的行号。rm_indexes中的1表示第1行(DF的第二行),three表示数据帧的第三行,等等(第一行是0)。此数据帧的索引列是时间戳。在

PS.我有许多与数据帧索引相同的时间戳。在


Tags: 数据rmdfnp时间数组arrayps
2条回答

尝试:

df.drop(df.index[rm_indexes])

示例

^{pr2}$

输出

    A   B   C
1   1   1   1
3   3   3   3
5   5   5   5
6   6   6   6
7   7   7   7
8   8   8   8

编辑,在OP提供进一步规范后:具有相同索引的多行

df = pd.DataFrame({"A":[0,1,2,3,4,5,6,7,8],
                   "B":[0,1,2,3,4,5,6,7,8],
                   "C":[0,1,2,3,4,5,6,7,8],},
                   index=["a","b","b","a","b","c","c","d","e"])
df['idx'] = df.index

pos = [1]
df.reset_index(drop=True, inplace=True)
df.drop(df.index[pos], inplace=True)
df.set_index('idx', inplace=True)

输出

    A   B   C
idx         
a   0   0   0
b   2   2   2
a   3   3   3
b   4   4   4
c   5   5   5
c   6   6   6
d   7   7   7
e   8   8   8

你可以简单地按索引删除。这将通过索引1、2、3、4…等删除df中的条目。。199在

df.reset_index()    #this will change the index from timestamp to 0,1,2...n-1
df.drop([1, 2, 3, 4, 34, 100, 154, 155, 199])  # will drop the rows
df.index = df['myTimeStamp']  # this will restore the index back to timestamp

相关问题 更多 >