填充 pandas DataFrame

Populating a pandas DataFrame

我有一个数据框df:

    AuthorID  Year  citations
0          1  1995         86
1          2  1995         22
2          3  1995         22
3          4  1995         22
4          5  1995         36
5          6  1995         25

和另一个我创建并初始化为零的数据帧 df2 其中每个索引代表 AuthorID 来自 df:

         1994  1995  1996  1997  1998  1999  2000  2001  2002  2003  2004  
1           0     0     0     0     0     0     0     0     0     0     0   
2           0     0     0     0     0     0     0     0     0     0     0   
3           0     0     0     0     0     0     0     0     0     0     0   
4           0     0     0     0     0     0     0     0     0     0     0   
5           0     0     0     0     0     0     0     0     0     0     0   
6           0     0     0     0     0     0     0     0     0     0     0   

现在我要做的是遍历 df 并将引文值添加到第二个矩阵中的正确位置。因此,如果我要根据上面的内容填写 df2,它将如下所示:

         1994  1995  1996  1997  1998  1999  2000  2001  2002  2003  2004  
1           0     86     0     0     0     0     0     0     0     0     0   
2           0     22     0     0     0     0     0     0     0     0     0   
3           0     22     0     0     0     0     0     0     0     0     0   
4           0     36     0     0     0     0     0     0     0     0     0   
5           0     25     0     0     0     0     0     0     0     0     0   
6           0     0     0     0     0     0     0     0     0     0     0   

这很简单。

现在我所做的是:

for index, row in df.iterrows():
     df2.iloc[row[0]][row[1]] = df2.iloc[row[0]][row[1]] + row[2]

但它一直给我以下信息:

IndexError: index out of bounds  

所以我尝试了:

for index, row in df.iterrows():
     df2.at[row[0], row[1]] = df2.at[row[0], row[1]] + row[2]

它给了我:

ValueError: At based indexing on an non-integer index can only have non-integer indexers

我也试过 df.iat 但还是不行。

不确定我做错了什么。当我检查 df.dtypes 他们都返回 int64

为什么你不能像这样旋转第一个数据框

>> df.pivot(index='AuthorID', columns='Year', values='citations')

这将带来所有年份,因为列和索引将是您的 AuthorID

因此,要实现您的目标还有很长的路要走:为每个 AuthorID 将 1/3 值分配给 1995 年以外的其他年份。

x 是您的数据框。

我们将为下面的每个 AuthorID 添加年份:1996、1997 和 1998,并存储在 y 数据框中。

y = pd.DataFrame([[i, y, 0] for y in [1996,1997,1998] for i in x.AuthorID], columns=['AuthorID','Year','citations'])
z = x.append(y)

下面,我们将 1995 年引用的 1/3 值分配给同一作者的所有其他年份。

for id in z['AuthorID'].unique():
    condition = (z['AuthorID']==id) & (z['Year']>1995)
    citation2 = (z.loc[(z['Year']==1995) & (z['AuthorID']==id),'citations']/3).values
    z['citations'][condition] = citation2

In [1541]: z.pivot(index='AuthorID', columns='Year', values='citations')
Out[1541]: 
Year      1995       1996       1997       1998
AuthorID                                       
1           86  28.666667  28.666667  28.666667
2           22   7.333333   7.333333   7.333333
3           22   7.333333   7.333333   7.333333
4           22   7.333333   7.333333   7.333333
5           36  12.000000  12.000000  12.000000
6           25   8.333333   8.333333   8.333333