1 回答
TA贡献1804条经验 获得超8个赞
没有魔法。只是一些常规操作。
(1) 统计文件中“独特”的文章
编辑:添加(快速而肮脏)代码以包含计数为零的文件名
# prevent repetitive counting
df = df.drop_duplicates()
# articles to be removed (the ones appeared more than once)
dup_articles = df["Articles"].value_counts()
dup_articles = dup_articles[dup_articles > 1].index
# remove duplicate articles and count
mask_dup_articles = df["Articles"].isin(dup_articles)
df_unique = df[~mask_dup_articles]
df_unique["Filename"].value_counts()
# N.B. all filenames not shown here of course has 0 count.
# I will add this part later on.
Out[68]:
Invasive Species.csv 1
Name: Filename, dtype: int64
# unique article count with zeros
df_unique_nonzero_count = df_unique["Filename"].value_counts().to_frame().reset_index()
df_unique_nonzero_count.columns = ["Filename", "count"]
df_all_filenames = pd.DataFrame(
data={"Filename": df["Filename"].unique()}
)
# join: all filenames with counted filenames
df_unique_count = df_all_filenames.merge(df_unique_nonzero_count, on="Filename", how="outer")
# postprocess
df_unique_count.fillna(0, inplace=True)
df_unique_count["count"] = df_unique_count["count"].astype(int)
df_unique_count
Out[119]:
Filename count
0 Invasive Species.csv 1
1 Forestry.csv 0
(2)统计文件之间的共同文章
# pick out records containing duplicate articles
df_dup = df[mask_dup_articles]
# merge on articles and then discard self- and duplicate pairs
df_merge = df_dup.merge(df_dup, on=["Articles"], suffixes=("1", "2"))
df_merge = df_merge[df_merge["Filename1"] > df_merge["Filename2"]] # alphabetical ordering
# count
df_ans2 = df_merge.groupby(["Filename1", "Filename2"]).count()
df_ans2.reset_index(inplace=True) # optional
df_ans2
Out[70]:
Filename1 Filename2 Articles
0 Invasive Species.csv Forestry.csv 1
添加回答
举报