我有一个很大的数据集,只能根据它的描述进行排序。描述通过将产品命名为: ProductVariantSpesification来描述该产品。我想整理这个变体并创建新的数据集,其中只包括那些有相同变体的数据集。
我试过:
400_variants = df[df[Description].str.contains("400")]它会是什么样子:
import pandas as pd
df = pd.read_excel(r'raw_data.xlsx', header = 0)
#Some code
df.to_excel(r'400.xlsx')我一开始是这样的:
Index Description Quantity Date
1 Ketchup400J 5 5/10/2019
2 Ketchup600J 4 5/11/2019
3 Ketchup800U 6 5/12/2019
4 Ketchup400U 7 5/13/2019
5 Ketchup600J 8 5/14/2019
6 Ketchup400U 9 5/15/2019
7 Ketchup800i 5 5/16/2019
8 … … …并希望400变体的输出为:
Index Description Quantity Date
1 Ketchup400J 5 5/10/2019
2 Ketchup400U 7 5/13/2019
3 Ketchup400U 9 5/15/2019发布于 2019-05-10 17:22:52
使用str.findall和groupby进行检查
for x , y in df.groupby(df.Description.str.findall(r'[0-9]+').str[0]):
print(y)
y.to_excel(str(x)+'.xlsx')
Index Description Quantity Date
0 1 Ketchup400J 5 5/10/2019
3 4 Ketchup400U 7 5/13/2019
5 6 Ketchup400U 9 5/15/2019
Index Description Quantity Date
1 2 Ketchup600J 4 5/11/2019
4 5 Ketchup600J 8 5/14/2019
Index Description Quantity Date
2 3 Ketchup800U 6 5/12/2019
6 7 Ketchup800i 5 5/16/2019更新
d={x : y for x , y in df.groupby(df.Description.str.findall(r'[0-9]+').str[0])}
d['400']发布于 2019-05-10 17:32:39
试试str.contains
>>> import pandas as pd
>>> df = pd.DataFrame({'Description':['Ketchup400J', 'Ketchup400K', 'Mustard400J', 'Ketchup300K','Mustard300K'],'Quantity':range(5),'Date':pd.date_range(start='1/1/2019',periods=5, freq='D')})
>>> df
Description Quantity Date
0 Ketchup400J 0 2019-01-01
1 Ketchup400K 1 2019-01-02
2 Mustard400J 2 2019-01-03
3 Ketchup300K 3 2019-01-04
4 Mustard300K 4 2019-01-05
>>> df[df.Description.str.contains('400')]
Description Quantity Date
0 Ketchup400J 0 2019-01-01
1 Ketchup400K 1 2019-01-02
2 Mustard400J 2 2019-01-03https://stackoverflow.com/questions/56082118
复制相似问题