我有一些 pandas DataFrame,我正在尝试找到一种好方法来计算和绘制 DataFrame 中每个唯一条目出现的次数。举个例子,如果我有以下 2 个 DataFrame:
year month
0 1900 1
1 1950 2
2 2000 3
year month
0 1900 1
1 1975 2
2 2000 3
我在想也许有一种方法可以将它们合并到一个 DataFrame 中,同时使用新列 counts
来跟踪年 + 月的唯一组合的次数
发生在任何 DataFrame 中。从那里我想我可以用散点图绘制年+月
组合及其相应的计数。
year month counts
0 1900 1 2
1 1950 2 1
2 2000 3 2
3 1975 2 1
有什么好的方法可以实现这一点吗?
最佳答案
concat
然后使用 groupby
agg
pd.concat([df1,df2]).groupby('year').month.agg(['count','first']).reset_index().rename(columns={'first':'month'})
Out[467]:
year count month
0 1900 2 1
1 1950 1 2
2 1975 1 2
3 2000 2 3
关于python - 结合 pandas DataFrames 来给出唯一的元素计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690757/