簡體   English   中英

從python中的現有列創建新列

[英]Creating new columns from existing column in python

我有一個看起來像這樣的數據框:

data = [['A', 1, 100], ['A', 3, 100], ['A', 2, 100], ['A', 3, 100], ['A', 5, 100]]
df =  pd.DataFrame(data, columns = ['?', 'Rating', 'Amount'])
    ?   Rating  Amount
0   A   1       100
1   A   3       100
2   A   2       100
3   A   3       100
4   A   5       100

我需要根據替代金額的評級值創建新列 - 看起來像這樣:

    ?   Rating  Amount  1   2   3   5
0   A   1       100     100 0   0   0
1   A   3       100     0   0   100 0
2   A   2       100     0   100 0   0
3   A   3       100     0   0   100 0
4   A   5       100     0   0   0   100

現在我有這個:

ratingnames = np.unique(list(df['Rating']))
ratingnames.sort()

d = pd.DataFrame(0, index=np.arange(len(df['Rating'])), columns=ratingnames)

for i in range(len(df['Rating'])):
    ratingvalue = df.loc[i, 'Rating']
    d.loc[i, ratingvalue] = df.loc[i, 'Amount']

df = pd.concat([df, d], axis = 1)

但我覺得它可以改進。 有什么建議? 謝謝!

IIUC,使用get_dummies和乘法與df['Amount'],然后concataxis=1

output = pd.concat((df,pd.get_dummies(df['Rating']).mul(df['Amount'],axis=0)),axis=1)

   ?  Rating  Amount    1    2    3    5
0  A       1     100  100    0    0    0
1  A       3     100    0    0  100    0
2  A       2     100    0  100    0    0
3  A       3     100    0    0  100    0
4  A       5     100    0    0    0  100

時間: 在此處輸入圖片說明

這將解決問題:

df=pd.concat([df, df.apply(lambda x: pd.Series({x["Rating"]: x["Amount"]}), axis=1).fillna(0).astype("int")], axis=1)

輸出:

   ?  Rating  Amount    1    2    3    5
0  A       1     100  100    0    0    0
1  A       3     100    0    0  100    0
2  A       2     100    0  100    0    0
3  A       3     100    0    0  100    0
4  A       5     100    0    0    0  100

暫無
暫無

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

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