统计重复值,删除重复项并保留计数和其他列

3

我正在从Excel文件格式中设置一个数据集,大约包含10,000行和55列。我挑选出要显示的相关列(数字和日期)。

现在,“数字”列有许多重复值,我想计数并删除这些重复项。同时,我想显示数字最后使用的日期。

举个例子:

Column 1 = Numbers [445, 446, 447, 449, 445, 451, 445, 466, 449, ...]
Column 2 = Date [4/26/2019,3/26/2019,3/15/2019,2/26/2019,12/26/2018,12/16/2018,11/26/2018,11/6/2018,11/01/2019,... ]

445和447是重复值;445在不同日期被计算了3次,449被计算了2次。

我想要创建的表格如下:

Column 1 = Numbers [445, 446, 447, 449, 451, 466, ...]
Column 2 = Date [4/26/2019,3/26/2019,3/15/2019,2/26/2019,12/16/2018,11/6/2018,,...]
Column 3 = Count [3,1,1,2,1,1,...]

即在新表中保留的日期是数字最后一次使用的最新日期。
import pandas as pd

data = pd.read_excel(r'ImportedFile.xlsx', header = 0)
df = data[['Number','Date']]
sold_total = df.pivot_table(index=['Number'], aggfunc='size')

下一步是什么? 谢谢


检查 df 的形状,然后使用 drop_duplicates() 函数,参数 keep='last',并将新形状从旧形状中减去。 - G. Anderson
2个回答

3

使用:

df['Count']=df.groupby('Column_1').transform('count')
df=df.drop_duplicates('Column_1')
print(df)

   Column_1   Column_2  Count
0       445 2019-04-26      3
1       446 2019-03-26      1
2       447 2019-03-15      1
3       449 2019-02-26      2
5       451 2018-12-16      1
7       466 2018-11-06      1

1

尝试:

# thanks anky_91 for reset_index()
df.groupby('Number').Date.agg(['max', 'count']).reset_index()

输出:

+----+----------+---------------------+---------+
|    |   Number | max                 |   count |
|----+----------+---------------------+---------|
|  0 |      445 | 2019-04-26 00:00:00 |       3 |
|  1 |      446 | 2019-03-26 00:00:00 |       1 |
|  2 |      447 | 2019-03-15 00:00:00 |       1 |
|  3 |      449 | 2019-11-01 00:00:00 |       2 |
|  4 |      451 | 2018-12-16 00:00:00 |       1 |
|  5 |      466 | 2018-11-06 00:00:00 |       1 |
+----+----------+---------------------+---------+

你如何使用漂亮的SQL风格表格自动格式化字符串? - ifly6
@ifly6:我使用tabulate包。 - Quang Hoang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接