我有兩個串列,如下所示:-
column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']
我想使用兩個串列創建一個資料框,以便 column2 的值必須相等地重復以創建一個資料框。我試圖實作它,但我得到如下輸出:-
import pandas as pd
import numpy as np
column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']
table1 = np.tile(column1, len(column2))
table2 = np.repeat(column2, len(column1))
df = pd.DataFrame({"table1": table1, "table2": table2})
print(df)
收到的輸出:-
table1 table2
0 30 bat
1 40 bat
2 50 bat
3 60 bat
4 90 bat
5 20 bat
6 30 bat
7 20 bat
8 30 bat
9 30 ball
10 40 ball
11 50 ball
12 60 ball
13 90 ball
14 20 ball
15 30 ball
16 20 ball
17 30 ball
18 30 tent
19 40 tent
20 50 tent
21 60 tent
22 90 tent
23 20 tent
24 30 tent
25 20 tent
26 30 tent
例外輸出:-
table1 table2
0 30 bat
1 40 bat
2 50 bat
3 60 ball
4 90 ball
5 20 ball
6 30 tent
7 20 tent
8 30 tent
有沒有更好的方法來獲得例外輸出?
uj5u.com熱心網友回復:
np.repeat像這樣使用:
df = pd.DataFrame({'table1': column1,
'table2': np.repeat(column2, len(column1) // len(column2))})
print(df)
# Output:
table1 table2
0 30 bat
1 40 bat
2 50 bat
3 60 ball
4 90 ball
5 20 ball
6 30 tent
7 20 tent
8 30 tent
uj5u.com熱心網友回復:
您正在使用的代碼將幫助您實作此結果。不需要在 column1 上作業,你可以試試這個它會回傳你想要的輸出
import pandas as pd
import numpy as np
column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']
# table1 = np.tile(column1, len(column2))
table2 = np.repeat(column2, len(column1)/len(column2))
df = pd.DataFrame({"table1": column1, "table2": table2})
print(df)
但在這種方法中 column1 必須是 column2 的倍數
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349346.html
上一篇:如何在R中創建一個包含n個用戶輸入物件(即`...`)的串列來處理不存在的物件?
下一篇:堆疊串列項-至少需要一個向量
