我有一个数据框架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
什么函数可以做到这一点?
考虑一个示例数据框架
df =
index column1
0 00
1 10
2 20
3 30
我们想要删除第2和第3个索引行。
方法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.
正如Dennis Golomazov的回答所建议的,使用逐行删除。您可以选择保留行。假设您有一个要删除的行索引列表,名为indices_to_drop。您可以将其转换为掩码,操作如下:
mask = np.ones(len(df), bool)
mask[indices_to_drop] = False
你可以直接使用这个索引:
df_new = df.iloc[mask]
这个方法的好处是,掩码可以来自任何来源:它可以是一个包含许多列的条件,也可以是其他条件。
真正好的事情是,你根本不需要原始DataFrame的索引,所以索引是否唯一并不重要。
缺点当然是不能用这种方法进行就地放置。
考虑一个示例数据框架
df =
index column1
0 00
1 10
2 20
3 30
我们想要删除第2和第3个索引行。
方法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.