2017-06-20 31 views
-3

我有一個像下面一個數據幀採樣爲CSV數據幀,如何代表使用熊貓

print (df) 
    column 1 column 2 column 3 
0 mobile  a Blanks 
1 mobile  b Blanks 
2 mobile  c cricket 
3 laptop  d cricket 
4 phone  e football 
5 phone  NaN football 
6 phone  g football 
7 phone  h football 

我想不相對於C1列 空白只有一行將抽樣的方法後,DF應該

​​

請告訴我哪種取樣方法適用於此。

+0

'mobile'似乎不是一次而是兩次??? –

回答

1

首先用NaN s刪除所有行dropna

如果只需要一個隨機行由column 1column 3分組可以通過numpy.random.choice

df = df.dropna() 

df = df.groupby(['column 1','column 3'], as_index=False) \ 
     .apply(lambda x: x.iloc[np.random.choice(np.arange(len(x)), 1)]) \ 
     .reset_index(drop=True) 
print (df) 
    column 1 column 2 column 3 
0 laptop  d cricket 
1 mobile  b Blanks 
2 mobile  c cricket 
3 phone  h football 

與自定義函數使用groupbyiloc隨機位置或使用sample

df = df.groupby(['column 1','column 3'], as_index=False) \ 
     .apply(lambda x: x.sample(n=1)) \ 
     .reset_index(drop=True) 
print (df) 
    column 1 column 2 column 3 
0 laptop  d cricket 
1 mobile  b Blanks 
2 mobile  c cricket 
3 phone  g football 
+0

如果我需要n = 2(2個表示)的樣本,我該怎麼辦? 我得到這個錯誤: – krish

+0

然後將'x.sample(n = 1)'改爲'x.sample(n = 2)',但每組中至少需要'2'行。 – jezrael

+0

在第一個解決方案中需要'.apply(lambda x:x.iloc [np.random.choice(np.arange(len(x)),2)])' – jezrael

0

這裏代碼:

import pandas as pd 

df = pd.read_table('44652428.tsv') 

print(df.groupby('column 1').first().reset_index()) 

這裏輸出:

column 1 column 2 column 3 
0 laptop  d cricket 
1 mobile  a Blanks 
2 phone  e football 

這裏輸入44652428.tsv

column 1 column 2 column 3 
mobile a Blanks 
mobile b Blanks 
mobile c cricket 
laptop d cricket 
phone e football 
phone NaN football 
phone g football 
phone h football 

這裏鏈接到文檔上read_tablegroupbyreset_index