我有一个包含产品库存信息的CSV文件。目前一些产品被列为五组,如"A BCD 1-5","A BCD 6-10“等。我需要将这些分组转换为5行,这样每一行都将是格式"A BCD 1","A BCD 2","A BCD 3”等。我在想,我将需要使用一堆不同的正则表达式来找到"1-5"," 6-10“,并从中创建新的行,但我有点卡住了。
df = pd.DataFrame([{'var1': 'a', 'var2': '1-5'},
{'var1': 'b', 'var2': '6-10'}])
从这个开始:
|Name|Inventory Number|
|:---|---:|
|x|A BCD 1-5|
|x|A BCD 6-10|
要这样做:
|Name|Inventory Number|
|:---|---:|
|x|A BCD 1|
|x|A BCD 2|
|x|A BCD 3|
|x|A BCD 4|
|x|A BCD 5|
|x|A BCD 6|
|x|A BCD 7|
|x|A BCD 8|
|x|A BCD 9|
|x|A BCD 10|
发布于 2021-07-02 01:03:50
另一种方式:
>>> df['Inventory Number'].str.extract(r'(.*) (\d+)-(\d+)') \
.dropna(how='all') \
.apply(lambda x: [f'{x[0]} {i}'
for i in np.arange(int(x[1]), int(x[2])+1)],
axis='columns').explode()
0 A BCD 1
0 A BCD 2
0 A BCD 3
0 A BCD 4
0 A BCD 5
1 A BCD 6
1 A BCD 7
1 A BCD 8
1 A BCD 9
1 A BCD 10
dtype: object
发布于 2021-07-02 00:55:26
这里有一种方法:
df[['Inventory Name', 'var2']] = df.pop(
'Inventory Number').str.rsplit(' ', n=1, expand=True)
df = df.assign(var2=df.var2.str.split(
'-').apply(lambda x: np.arange(int(x[0]), int(x[1])+1))).explode('var2')
df = df.astype(str).set_index('Name').agg(
' '.join, 1).reset_index(name='Inventory Number')
https://stackoverflow.com/questions/68214036
复制相似问题