我有一个学术期刊的数据集。如果论文发表在排名靠前的期刊上,变量Top Journal
是一个等于1的虚拟变量。Publication Month
是论文发表的月份。author1
,author2
等是在这一行中撰写特定论文的作者。
对于每个作者,我想统计一下以前在顶级期刊上发表的文章的数量。因此,我想要统计他/她的名字在authorX
专栏中之前出现的所有次数,但仅当该论文发表在顶级期刊上时。
df = pd.DataFrame({'Top Journal': [1,0,1],
'Publication Year': [2020, 2020, 2020],
'Publication Month': [8,8,7],
'author1': ['Hendren, Nathaniel', 'Backus, Matthew','Enke, Benjamin'],
'author2': ['Sprung-Keyser, Ben', 'Blake, Thomas', 'Hendren, Nathaniel'],
'author3': [None,'Larsen, Brad', None ]},
index = ['UID1', 'UID2', 'UID3'])
输出应如下所示:
Top Publication Publication author1 author2 author3 previous_publications1 previous_publications2 previous_publications3
Journal Year Month
1 2020 8 Hendren, Nathaniel Sprung-Keyser, Ben None 1 0 None
0 2020 8 Backus, Matthew Blake, Thomas Larsen, Brad 0 0 0
1 2020 7 Enke, Benjamin Hendren, Nathaniel None 0 0 None
重要提示:如果作者姓名在author1
中被提及一次,它可能会出现在另一个观察中的任何其他位置(例如author6
)。
以前发表的顶级期刊的数量应该显示在新的列previous_publications1
,previous_publications2
中,其中的数字指的是各自的作者。因此,第一篇论文(亨德伦,纳撒尼尔)的author1计数比亨德伦,纳撒尼尔第二次出现在第三行时的出版物数量更多。
发布于 2020-11-10 03:19:08
使用数据帧:
df = pd.DataFrame({'Top Journal': [1,0,1],
'Publication Year': [2020, 2020, 2020],
'Publication Month': [8,8,7],
'author1': ['Hendren, Nathaniel', 'Backus, Matthew','Enke, Benjamin'],
'author2': ['Sprung-Keyser, Ben', 'Blake, Thomas', 'Hendren, Nathaniel'],
'author3': [None,'Larsen, Brad', None]},
index = ['UID1', 'UID2', 'UID3'])
您的author
列的格式使wide_to_long
成为一个很好的选择,因为您可以使用author
作为存根名称,将所有三个author列合并为一个,这样您就可以累计统计以前有多少个出版物;但是,为了使用cumcount
,我们需要在一个列中包含相关数据。在此基础上,使用unstack(3)
将第四个索引列('author #')放入列标题中,并使用“长到宽”将其转换回原始格式。然后去掉多索引,使用带有df.columns = [''.join(col) for col in df.columns]
的原始列名,但首先author #
列名必须是带有.rename({1: '1', 2: '2', 3: '3'}, axis=1)
的字符串
df = (pd.wide_to_long(df, stubnames='author', i=['Top Journal', 'Publication Year', 'Publication Month'], j='author #')
.sort_values(['Publication Year', 'Publication Month']))
df['previous_publications'] = df.groupby('author').cumcount()
df = df[~df['author'].isnull()].unstack(3).rename({1: '1', 2: '2', 3: '3'}, axis=1).fillna('None')
df.columns = [''.join(col) for col in df.columns]
df
Out[1]:
author1 \
Top Journal Publication Year Publication Month
0 2020 8 Backus, Matthew
1 2020 7 Enke, Benjamin
8 Hendren, Nathaniel
author2 \
Top Journal Publication Year Publication Month
0 2020 8 Blake, Thomas
1 2020 7 Hendren, Nathaniel
8 Sprung-Keyser, Ben
author3 \
Top Journal Publication Year Publication Month
0 2020 8 Larsen, Brad
1 2020 7 None
8 None
previous_publications1 \
Top Journal Publication Year Publication Month
0 2020 8 0.0
1 2020 7 0.0
8 1.0
previous_publications2 \
Top Journal Publication Year Publication Month
0 2020 8 0.0
1 2020 7 0.0
8 0.0
previous_publications3
Top Journal Publication Year Publication Month
0 2020 8 0.0
1 2020 7 NaN
8 NaN
https://stackoverflow.com/questions/64756045
复制相似问题