如何从 Pandas 数据框中删除一列行?
- 2025-01-13 08:53:00
- admin 原创
- 100
问题描述:
我有一个数据框 df:
>>> df
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20060630 6.590 NaN 6.590 5.291
20060930 10.103 NaN 10.103 7.981
20061231 15.915 NaN 15.915 12.686
20070331 3.196 NaN 3.196 2.710
20070630 7.907 NaN 7.907 6.459
然后我想删除列表中指示的具有特定序列号的行,假设这里[1,2,4],
剩下:
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20061231 15.915 NaN 15.915 12.686
20070630 7.907 NaN 7.907 6.459
如何或者什么功能可以做到这一点?
解决方案 1:
使用DataFrame.drop并传递一系列索引标签:
In [65]: df
Out[65]:
one two
one 1 4
two 2 3
three 3 2
four 4 1
In [66]: df.drop(df.index[[1,3]])
Out[66]:
one two
one 1 4
three 3 2
解决方案 2:
请注意,当您想要执行插入操作时,使用“inplace”命令可能很重要。
df.drop(df.index[[1,3]], inplace=True)
因为您的原始问题没有返回任何内容,所以应该使用此命令。http
://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.drop.html
解决方案 3:
如果 DataFrame 很大,并且要删除的行数也很大,那么简单的通过索引删除df.drop(df.index[])
会花费太多时间。
在我的例子中,我有一个多索引浮点数 DataFrame 100M rows x 3 cols
,其中有 ,我需要10k
从中删除行。我发现最快的方法是删除take
剩余的行,这很违反直觉。
设为indexes_to_drop
要删除的位置索引数组([1, 2, 4]
在问题中)。
indexes_to_keep = set(range(df.shape[0])) - set(indexes_to_drop)
df_sliced = df.take(list(indexes_to_keep))
在我的例子中,这花费了20.5s
,而简单的df.drop
花费5min 27s
并消耗了大量内存。 生成的 DataFrame 是相同的。
解决方案 4:
我用一种更简单的方法解决了这个问题——只需两步。
创建一个包含不需要的行/数据的数据框。
使用此不需要的数据框的索引从原始数据框中删除行。
示例:
假设您有一个数据框 df,其中包含许多列,其中包括整数“年龄”。现在假设您想删除所有以“年龄”为负数的行。
df_age_negative = df[ df['Age'] < 0 ] # Step 1
df = df.drop(df_age_negative.index, axis=0) # Step 2
希望这会更简单并且能够帮助您。
解决方案 5:
您还可以将标签本身(而不是索引标签系列)传递给DataFrame.drop :
In[17]: df
Out[17]:
a b c d e
one 0.456558 -2.536432 0.216279 -1.305855 -0.121635
two -1.015127 -0.445133 1.867681 2.179392 0.518801
In[18]: df.drop('one')
Out[18]:
a b c d e
two -1.015127 -0.445133 1.867681 2.179392 0.518801
这相当于:
In[19]: df.drop(df.index[[0]])
Out[19]:
a b c d e
two -1.015127 -0.445133 1.867681 2.179392 0.518801
解决方案 6:
如果我想删除具有索引的行x
,我会执行以下操作:
df = df[df.index != x]
如果我想删除多个索引(假设这些索引在列表中unwanted_indices
),我会这样做:
desired_indices = [i for i in len(df.index) if i not in unwanted_indices]
desired_df = df.iloc[desired_indices]
解决方案 7:
这里有一个比较具体的例子,我想展示一下。假设您的某些行中有许多重复条目。如果您有字符串条目,则可以轻松使用字符串方法找到要删除的所有索引。
ind_drop = df[df['column_of_strings'].apply(lambda x: x.startswith('Keyword'))].index
现在使用索引删除这些行
new_df = df.drop(ind_drop)
解决方案 8:
仅使用索引参数来删除行:-
df.drop(index = 2, inplace = True)
对于多行:-
df.drop(index=[1,3], inplace = True)
解决方案 9:
在对 @theodros-zelleke 的回答的评论中,@j-jones 询问如果索引不唯一该怎么办。我不得不处理这种情况。我所做的是在调用之前重命名索引中的重复项drop()
,如下所示:
dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)
其中rename_duplicates()
是我定义的函数,它遍历索引元素并重命名重复项。我使用了与pd.read_csv()
列相同的重命名模式,即 ,"%s.%d" % (name, count)
其中name
是行的名称,count
是它之前出现的次数。
解决方案 10:
如上所述,根据布尔值确定索引,例如
df[df['column'].isin(values)].index
与使用此方法确定索引相比,占用的内存更多
pd.Index(np.where(df['column'].isin(values))[0])
像这样应用
df.drop(pd.Index(np.where(df['column'].isin(values))[0]), inplace = True)
处理大型数据帧和有限内存时,此方法很有用。
解决方案 11:
要删除索引为 1, 2, 4 的行,可以使用:
df[~df.index.isin([1, 2, 4])]
波浪号运算~
符对方法的结果取反isin
。另一种选择是删除索引:
df.loc[df.index.drop([1, 2, 4])]
解决方案 12:
看看下面的数据框 df
df
column1 column2 column3
0 1 11 21
1 2 12 22
2 3 13 23
3 4 14 24
4 5 15 25
5 6 16 26
6 7 17 27
7 8 18 28
8 9 19 29
9 10 20 30
让我们删除列 1 中所有具有奇数的行
创建 column1 中所有元素的列表,并仅保留偶数元素(您不想删除的元素)
keep_elements = [x for x in df.column1 if x%2==0]
所有包含其列 1 中的值的行都[2, 4, 6, 8, 10]
将被保留或不会被删除。
df.set_index('column1',inplace = True)
df.drop(df.index.difference(keep_elements),axis=0,inplace=True)
df.reset_index(inplace=True)
我们将列 1 作为索引并删除所有不需要的行。然后我们将索引重置回来。df
column1 column2 column3
0 2 12 22
1 4 14 24
2 6 16 26
3 8 18 28
4 10 20 30
解决方案 13:
正如Dennis Golomazov 的回答所建议的那样,使用drop
删除行。您可以选择保留行。假设您有一个要删除的行索引列表,名为indices_to_drop
。您可以将其转换为掩码,如下所示:
mask = np.ones(len(df), bool)
mask[indices_to_drop] = False
您可以直接使用该索引:
df_new = df.iloc[mask]
这种方法的优点是它mask
可以来自任何来源:它可以是涉及许多列的条件,也可以是其他东西。
真正好的是,您根本不需要原始 DataFrame 的索引,因此索引是否唯一并不重要。
当然,缺点是您不能使用此方法进行就地放置。
解决方案 14:
这对我有用
# Create a list containing the index numbers you want to remove
index_list = list(range(42766, 42798))
df.drop(df.index[index_list], inplace =True)
df.shape
这应该会删除创建范围内的所有索引
解决方案 15:
考虑一个示例数据框
df =
index column1
0 00
1 10
2 20
3 30
我们要删除第二和第三索引行。
方法 1:
df = df.drop(df.index[2,3])
or
df.drop(df.index[2,3],inplace=True)
print(df)
df =
index column1
0 00
3 30
#This approach removes the rows as we wanted but the index remains unordered
方法 2
df.drop(df.index[2,3],inplace=True,ignore_index=True)
print(df)
df =
index column1
0 00
1 30
#This approach removes the rows as we wanted and resets the index.