[英]How do I create new columns based off of a list derived from an existing column in python/pandas?
[英]How to create new column based off values from existing columns in pandas
我有一個包含 171 行和 11 列的數據框。
11 列的值要么是 0 要么是 1 我如何創建一個新列,它要么是 0 要么是 1,具體取決於現有列的多數是 0 還是 1?
你可以做
(df.sum(axis=1)>df.shape[1]/2)+0
使用行的mean
並通過DataFrame.gt
進行比較以獲取更大或通過DataFrame.ge
進行比較以獲取大於或等於0.5
(如果0
和1
的數量相同則取決於輸出),最后通過Series.astype
將掩碼轉換為整數:
np.random.seed(20193)
df = pd.DataFrame(np.random.choice([0,1], size=(5, 4)))
df['new'] = df.mean(axis=1).gt(0.5).astype(int)
print (df)
0 1 2 3 new
0 1 1 0 0 0
1 1 1 1 0 1
2 0 0 1 0 0
3 1 1 0 1 1
4 1 1 1 1 1
np.random.seed(20193)
df = pd.DataFrame(np.random.choice([0,1], size=(5, 4)))
df['new'] = df.mean(axis=1).ge(0.5).astype(int)
print (df)
0 1 2 3 new
0 1 1 0 0 1
1 1 1 1 0 1
2 0 0 1 0 0
3 1 1 0 1 1
4 1 1 1 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.