Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:基于其他列添加新列_Python_Pandas - Fatal编程技术网

Python 熊猫:基于其他列添加新列

Python 熊猫:基于其他列添加新列,python,pandas,Python,Pandas,给定这样的数据帧: >>>df paper year citation 0 A 2000 1 1 A 2001 2 2 B 2000 3 3 B 2001 4 4 B 2002 5 我想添加三列(即2000年、2001年、2002年),因此结果将是: >>>dfnew paper year2000 year2001 year2002 0 A 1 2

给定这样的数据帧:

>>>df
  paper year citation
0   A   2000    1
1   A   2001    2
2   B   2000    3
3   B   2001    4
4   B   2002    5
我想添加三列(即2000年、2001年、2002年),因此结果将是:

>>>dfnew
  paper year2000 year2001 year2002
0   A      1        2         0
1   B      3        4         5

您可以使用
pivot\u table
values='引文'
rows='paper'
columns='year'
并通过
fill\u value=0

In [9]: pd.pivot_table(df, values='citation', rows='paper', columns='year', fill_value=0)
Out[9]:
year   2000  2001  2002
paper
A         1     2     0
B         3     4     5
或者,您也可以像这样使用
pd.crosstab

In [10]: pd.crosstab(index=df['paper'], columns=df['year'], values=df['citation'],
                     aggfunc=pd.np.sum)
Out[15]:
year   2000  2001  2002
paper
A         1     2   NaN
B         3     4     5

谢谢这正是我想要的。