gpt4 book ai didi

python-3.x - 获得虚拟对象后重新排列列

转载 作者:行者123 更新时间:2023-12-02 20:36:27 25 4
gpt4 key购买 nike

       A            B            C               D              E
0 165349.20 136897.80 471784.10 New York 192261.83
1 162597.70 151377.59 443898.53 California 191792.06
2 153441.51 101145.55 407934.54 Florida 191050.39
3 144372.41 118671.85 383199.62 New York 182901.99
4 142107.34 91391.77 366168.42 Florida 166187.94

使用后df = pd.get_dummies(df, columns=['D'])

        A            B              C           E      D_New York    D_California     D_Florida
0 165349.20 136897.80 471784.10 192261.83 0 0 1
1 162597.70 151377.59 443898.53 191792.06 1 0 0
2 153441.51 101145.55 407934.54 191050.39 0 1 0
3 144372.41 118671.85 383199.62 182901.99 0 0 1
4 142107.34 91391.77 366168.42 166187.94 0 1 0

有没有一种方法可以使输出看起来像这样而不使用 df[['A','B','C','D_Califorina','D_New York','D_Florida','E']] ?

        A            B          C      D_New York    D_California     D_Florida     E
0 165349.20 136897.80 471784.10 0 0 1 192261.83
1 162597.70 151377.59 443898.53 1 0 0 191792.06
2 153441.51 101145.55 407934.54 0 1 0 191050.39
3 144372.41 118671.85 383199.62 0 0 1 182901.99
4 142107.34 91391.77 366168.42 0 1 0 166187.94

最佳答案

针对可能未按排序顺序的列的通用解决方案:
找到要虚拟化并相应连接的列的位置

j = df.columns.get_loc('D')

left = df.iloc[:, :j]
dumb = pd.get_dummies(df[['D']])
rite = df.iloc[:, j+1:]

pd.concat([left, dumb, rite], axis=1)

A B C D_California D_Florida D_New York E
0 165349.20 136897.80 471784.10 0 0 1 192261.83
1 162597.70 151377.59 443898.53 1 0 0 191792.06
2 153441.51 101145.55 407934.54 0 1 0 191050.39
3 144372.41 118671.85 383199.62 0 0 1 182901.99
4 142107.34 91391.77 366168.42 0 1 0 166187.94

关于python-3.x - 获得虚拟对象后重新排列列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com