我有包含數字 x =(1,2,3,4,5,6,7,8) 的串列我還有一個包含 1000 行的資料框。我需要的是將串列中的數字分配到一列/創建一個新列,以便第 1-8 行包含數字 1-8,但之后它再次開始,因此第 9 行應包含數字 1 和很快。這看起來很容易,但不知何故我無法做到這一點。
uj5u.com熱心網友回復:
from math import ceil
df['new_column'] = (x*(ceil(len(df)/len(x))))[:len(df)]
uj5u.com熱心網友回復:
這里有兩種可能的方式(這里的例子有 3 個要重復的專案):
與 numpy.tile
df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = np.tile(x, len(df)//len(x) 1)[:len(df)]
和 itertools
from itertools import cycle, islice
df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = list(islice(cycle(x), len(df
輸入:
col
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
輸出:
col newcol
0 0 1
1 1 2
2 2 3
3 3 1
4 4 2
5 5 3
6 6 1
7 7 2
8 8 3
9 9 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343740.html
下一篇:提取檔案中兩個句子之間的行
