pandas 如何删掉第一行_Python:Pandas – 按组删除第一行
您可以使用groupby / transform來準備一個布爾掩碼,對于您想要的行,該掩碼為True,對于您不想要的行,則為False.一旦有了這樣的布爾掩碼,就可以使用df.loc [mask]選擇子DataFrame:
import numpy as np
import pandas as pd
df = pd.DataFrame(
{'ID': [10001, 10001, 10001, 10002, 10002, 10002, 10003, 10003, 10003],
'PRICE': [14.5, 14.5, 14.5, 15.125, 14.5, 14.5, 14.5, 14.5, 15.0],
'date': [19920103, 19920106, 19920107, 19920108, 19920109, 19920110,
19920113, 19920114, 19920115]},
index = range(1,10))
def mask_first(x):
result = np.ones_like(x)
result[0] = 0
return result
mask = df.groupby(['ID'])['ID'].transform(mask_first).astype(bool)
print(df.loc[mask])
產量
ID PRICE date
2 10001 14.5 19920106
3 10001 14.5 19920107
5 10002 14.5 19920109
6 10002 14.5 19920110
8 10003 14.5 19920114
9 10003 15.0 19920115
既然你對效率感興趣,這里有一個基準:
import timeit
import operator
import numpy as np
import pandas as pd
N = 10000
df = pd.DataFrame(
{'ID': np.random.randint(100, size=(N,)),
'PRICE': np.random.random(N),
'date': np.random.random(N)})
def using_mask(df):
def mask_first(x):
result = np.ones_like(x)
result[0] = 0
return result
mask = df.groupby(['ID'])['ID'].transform(mask_first).astype(bool)
return df.loc[mask]
def using_apply(df):
return df.groupby('ID').apply(lambda group: group.iloc[1:, 1:])
def using_apply_alt(df):
return df.groupby('ID', group_keys=False).apply(lambda x: x[1:])
timing = dict()
for func in (using_mask, using_apply, using_apply_alt):
timing[func] = timeit.timeit(
'{}(df)'.format(func.__name__),
'from __main__ import df, {}'.format(func.__name__), number=100)
for func, t in sorted(timing.items(), key=operator.itemgetter(1)):
print('{:16}: {:.2f}'.format(func.__name__, t))
報告
using_mask : 0.85
using_apply_alt : 2.04
using_apply : 3.70
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的pandas 如何删掉第一行_Python:Pandas – 按组删除第一行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三顾茅庐的主人公是谁(刘备三顾茅庐的历史
- 下一篇: 霜纹布哪里刷的快