简体   繁体   English

从现有行生成新的 Dataframe 列

[英]Generating New Dataframe columns from existing rows

I am looking into some basketball data, where I have some dataframe that would look like (for one team only...baby steps)我正在研究一些篮球数据,其中有一些 dataframe 看起来像(仅适用于一支球队......婴儿步骤)

df = pd.DataFrame({'PlayId':[1,1,1,1,1],'Player':['A','B','C','D','E'],'Ball':[0,0,1,0,0],'Pos':[1, 4, 10, 15, 20 ],'Speed':[1,2,3,4,5]})

I create a column for distance from Ball=1 (generalized to many PlayId):我为距 Ball=1 的距离创建一个列(推广到许多 PlayId):

df['DistanceToBall'] = np.abs(df.Pos-df.Pos[df.groupby('PlayId')['Ball'].transform('idxmax')].reset_index(drop=True))

Next I want to make this into a single row that contains the information of Ball = 1接下来我想把它变成包含 Ball = 1 信息的单行

newdf = df.loc[df.Ball==1,:]

Now I want to add columns about the information of Pos and Speed based on DistanceToBall.现在我想添加有关基于 DistanceToBall 的 Pos 和 Speed 信息的列。 My new columns would be closest1,closest2,closest3,closest4 which would have values of their position, so in order(15,4,1,20).我的新列将是最接近 1、最接近 2、最接近 3、最接近 4,它们的值将是 position,因此按顺序排列(15、4、1、20)。 I am unsure of how to do that, especially in the case where I have many different 'PlayId'.我不确定如何做到这一点,尤其是在我有许多不同的“PlayId”的情况下。

EDIT: Expected Output:编辑:预计 Output:

 PlayId Player  Ball    Pos Speed   DistanceToBall  closest1    closest2    closest3    closest4    speed1  speed2  speed3  speed4
2   1   C   1   10  3   0   15  4   1   20  4   2   1   5

This will append to newdf the 4 closest players' Pos , sorted by DistanceToBall :这将 append 到newdf 4 个最近玩家的Pos ,按DistanceToBall排序:

for i in range(4):
    newdf.loc[:, 'closest{}'.format(i+1)] = \
        df.sort_values(by='DistanceToBall')['Pos'].values[i]
for i in range(4):
    newdf.loc[:, 'speed{}'.format(i + 1)] = \
        df.sort_values(by='DistanceToBall')['Speed'].values[i]
Out[22]: 
   PlayId Player  Ball  Pos  Speed  ...  closest4  speed1  speed2  speed3  speed4
2       1      C     1   10      3  ...       1.0     3.0     4.0     2.0     1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM