从python中的现有列创建新列
我有一个看起来像这样的数据框:从python中的现有列创建新列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个看起来像这样的数据框: 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 1 2 3 5 0 A 1 100 10
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 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,使用并与df['Amount']相乘,
然后在轴=1上:
output = pd.concat((df,pd.get_dummies(df['Rating']).mul(df['Amount'],axis=0)),axis=1)
时间:
IIUC,使用df['Amount']并与之相乘,
然后在轴=1上:
output = pd.concat((df,pd.get_dummies(df['Rating']).mul(df['Amount'],axis=0)),axis=1)
时间:
这将实现以下目的:
df=pd.concat([df,df.apply(lambda x:pd.Series({x[“Rating”]:x[“Amount”]}),axis=1)。fillna(0)。astype(“int”)],axis=1)
输出:
?评税金额1 2 3 5
0 A 1100 00 0 0 0 0
1A31000100
2 A 2 100 0 100 0 0 0 0
3 A 3 100 0 0 100 0
4 A 5 100 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)
输出:
?评税金额1 2 3 5
0 A 1100 00 0 0 0 0
1A31000100
2 A 2 100 0 100 0 0 0 0
3 A 3 100 0 0 100 0
4 A 5 100 0 0 100
@ecaines在熊猫中不需要时,不应使用应用
,尤其是轴=1
非常慢。添加了一些计时测试来演示我在测试中的意思,感谢您在中添加这些。非常helpful@ecaines没问题..happy coding:)@ecaines您不应该在pandas中不需要时使用apply
,尤其是axis=1
非常慢。添加了一些计时测试来演示我在测试中的意思,感谢您在中添加这些。非常helpful@ecaines没问题..快乐编码:)
? 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