簡體   English   中英

遍歷熊貓行並根據其他列中的值設置列值

[英]iterate over pandas rows and set column values based on values in other column

我有一個數據框,其中一列(col1)包含Y或N值。我想根據col1中的值將值(隨機數,不是重復數)分配給下一列(col2)-如果col1中的值等於N,則col2中的值將是某個數字,如果col1中的值等於Y,則col2中的值將重復前一個。 我試圖創建一個for循環並使用df.iterrows()遍歷行,但是col2中的數字對於所有N都是相等的。

我要獲取的數據框示例:

df = pd.DataFrame([[N, Y, Y, N, N, Y], [1, 1, 1, 2, 3, 3]])

其中,每個新的N個新數字在其他列中分配,而每個Y的數字均與上一行相同。

假設一個DataFrame df:

df = pd.DataFrame(['N', 'Y', 'Y', 'N', 'N', 'Y'], columns=['YN'])
    YN
0   N
1   Y
2   Y
3   N
4   N
5   Y

使用itertuples (無重復):

np.random.seed(42)
arr = np.arange(1, len(df[df.YN == 'N']) + 1)
np.random.shuffle(arr)

cnt = 0
for idx, val in enumerate(df.itertuples()):
    if df.YN[idx] == 'N':
        df.loc[idx, 'new'] = arr[cnt]
        cnt += 1
    else:
        df.loc[idx, 'new'] = np.NaN
df.new = df.new.ffill().astype(int)
df
    YN  new
0   N   1
1   Y   1
2   Y   1
3   N   2
4   N   3
5   Y   3

使用apply (可能會在較小的數字范圍內出現重復):

np.random.seed(42)
df['new'] = df.YN.apply(lambda x: np.random.randint(10) if x == 'N' else np.NaN).ffill().astype(int)
    YN  new
0   N   6
1   Y   6
2   Y   6
3   N   3
4   N   7
5   Y   7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM