2017-09-26 151 views
0

我有一個數據框,我想'雙'(或三倍,或....)。我並不試圖將數據框與自身連接起來,即將df的一個完整副本堆疊在df的另一個完整副本的頂部。在熊貓數據框中重複行

與此開始:

import pandas as pd 
from io import StringIO 
from IPython.display import display 

A_csv = """country 
Afghanistan 
Brazil 
China""" 
with StringIO(A_csv) as fp: 
    A = pd.read_csv(fp) 
display(A) 

結果

 country 
0 Afghanistan 
1  Brazil 
2  China 

我想是這樣的;索引和縮進並不那麼重要。

 country 
0 Afghanistan 
1 Afghanistan 
2 Brazil 
3 Brazil 
4 China 
5 China 

回答

0

使用np.repeat

df = pd.DataFrame(A.values.repeat(2), columns=A.columns) 
df 

     country 
0 Afghanistan 
1 Afghanistan 
2  Brazil 
3  Brazil 
4  China 
5  China 

對於ND dataframes,溶液應使用axis參數repeat擴展:

df = pd.DataFrame(A.values.repeat(2, axis=0), columns=A.columns) 
+0

上的3x3 DF嘗試這給出這樣的錯誤:ValueError異常:傳遞的值的形狀爲(1,18),指數暗示(3,18);有沒有辦法讓這個更大的DF的工作? – cumin

+0

@cumin是的,添加一個「axis = 1」參數來重複。 –

+0

df = pd.DataFrame(A.values.repeat(2,axis = 1),columns = A.columns)ValueError:傳遞值的形狀爲(6,3),索引暗示(3,3) – cumin

0

您可以使用np.repeat

pd.DataFrame(np.repeat(df['country'], 2)).reset_index(drop = True) 

    country 
0 Afghanistan 
1 Afghanistan 
2 Brazil 
3 Brazil 
4 China 
5 China 
0

通過使用pd.concat

pd.concat([df]*2,axis=0).sort_index().reset_index(drop=True) 
Out[56]: 
     country 
0 Afghanistan 
1 Afghanistan 
2  Brazil 
3  Brazil 
4  China 
5  China