亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

以寬格式制作 pandas df 并將值取消連接到不同的列

以寬格式制作 pandas df 并將值取消連接到不同的列

三國紛爭 2022-07-05 19:45:47
我在標題中解釋問題時有點麻煩偶然地,我們將 Pandas 數據框轉向了這個:df = pd.DataFrame(np.array([[1,1,2], [1,2,1], [2,1,2], [2,2,2],[3,1,3]]),columns=['id', '3s', 'score'])id   3s  score1    1   21    2   12    1   2             2    2   2                 3    1   3但是我們需要取消堆疊,所以 df 看起來像這樣(原始版本): '3s' 列 'unpivots' 到由 3 個具有 0 和 1 的有序列按順序相加的離散集。因此,如果我們有'3s'= 2相應的列(第二組 3s)中'score'= 2的值將是(按順序排列 3 個中的 2 個)[1,1,0]['4','5','6']iddf2 = pd.DataFrame(np.array([[1,1,1,0,1,0,0], [2,1,1,0,1,1,0], [3,1,1,1,np.nan,np.nan,np.nan] ]),columns=['id', '1', '2','3','4','5','6'])id   1   2   3   4   5   61    1   1   0   1   0   02    1   1   0   1   1   0      3    1   1   1 非常感謝任何幫助! (請救救我)
查看完整描述

2 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

利用:


n = 3

df2 = df.reindex(index = df.index.repeat(n))

new_df = (df2.assign(score = df2['score'].gt(df2.groupby(['id','3s'])

                                                .id

                                                .cumcount())

                                         .astype(int),

                     columns = df2.groupby('id').cumcount().add(1))

             .pivot_table(index = 'id',

                          values='score',

                          columns = 'columns',

                          fill_value = '')

             .rename_axis(columns = None)

             .reset_index())

print(new_df)

輸出


   id    1    2    3  4  5  6

0   1  1.0  1.0  0.0  1  0  0

1   2  1.0  1.0  0.0  1  1  0

2   3  1.0  1.0  1.0         

如果你愿意,你可以使用fill_value = 0


   id  1  2  3  4  5  6

0   1  1  1  0  1  0  0

1   2  1  1  0  1  1  0

2   3  1  1  1  0  0  0


查看完整回答
反對 回復 2022-07-05
?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

這應該可以解決問題:


for gr in df.groupby('3s').groups:

    for i in range(1,4):

        df[str(i+(gr-1)*3)]=np.where((df['3s'].eq(gr))&(df['score'].ge(i)), 1,0)

df=df.drop(['3s', 'score'], axis=1).groupby('id').max().reset_index()

輸出:


   id  1  2  3  4  5  6

0   1  1  1  0  1  0  0

1   2  1  1  0  1  1  0

2   3  1  1  1  0  0  0


查看完整回答
反對 回復 2022-07-05
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號