我想计算一下只有连续的发票的数量。我试着将日期时间转换为字符串,然后用下面的代码计数,但我认为我把它搞得太复杂了。有什么建议吗?
date_strs = df['Invoice Date']
df.dropna(how='all')
dates = [datetime.strptime(str(d, "%m-%d-%Y")) for d in date_strs]
date_ints = set([d.toordinal() for d in dates])
if len(date_ints) == 1:
print("unique")
elif max(date_ints) - min(date_ints) == len(date_ints) - 1:
print("consecutive")
else:
print ("not consecutive")发布于 2021-08-24 20:15:35
你可以这样做:
import pandas as pd
d = {'Vender ID': {0: 8555, 1: 8555, 2: 8555, 3: 1044, 4: 1044, 5: 1044, 6: 1044},
'Vendor Name': {0: 'Macys',
1: 'Macys',
2: 'Macys',
3: 'JCPenny',
4: 'JCPenny',
5: 'JCPenny',
6: 'JCPenny'},
'Invoice Date': {0: '1/1/2020',
1: '1/2/2020',
2: '1/3/2020',
3: '2/1/2020',
4: '2/2/2020',
5: '2/3/2020',
6: '2/5/2020'},
'Invoice Number': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7}}
df = pd.DataFrame(d)
# fix time format
df['Invoice Date'] = pd.to_datetime(df['Invoice Date'])
# auxillary column to find sequences
df = df.sort_values(['Vender ID', 'Vendor Name', 'Invoice Date'])
df['continue'] = df['Invoice Date'].diff().dt.days.ne(1).cumsum()
# find time sequences
val_count = df['continue'].value_counts()
val_count = val_count[val_count.gt(1)].index.tolist()
# filter and group by Vendor
df[df['continue'].isin(val_count)].groupby(['Vendor Name'])['Vendor Name'].count()
# Vendor Name
# JCPenny 3
# Macys 3https://stackoverflow.com/questions/68913318
复制相似问题