我的数据框的一个小样本就是这种格式
**shop** **product** **location** **time** **count_products**
store1 ,A,B,C X 8.30 pm 3
store1 ,G,F Y 8.41 pm 2
store1 ,C,D,T,R Z 9.02 pm 4
现在我想拆分产品列。我知道 str.split 可以分割特殊字符,这样我就可以分割列。我喜欢生成的输出应具有以下格式,
**shop** **product** **location** **time** **count_products**
store1 A X 8.30 pm 3
store1 B X 8.30 pm 3
store1 C X 8.30 pm 3
store1 G Y 8.41 pm 2
store1 F Y 8.41 pm 2
store1 C Z 9.02 pm 4
store1 D Z 9.02 pm 4
store1 T Z 9.02 pm 4
store1 R Z 9.02 pm 4
我正在使用 pandas 和 numpy。您能否指导我如何继续获得上述输出?提前致谢。
最佳答案
您可以使用str.strip
用于删除 ,
, str.split
与 stack
用于为 join
创建系列
到原始的DataFrame
。
最后reset_index
为了避免 index
中出现重复,并通过 reindex_axis
对列名称重新排序:
print (
df.pop('**product**')
.str
.strip(',')
.str
.split(',',expand=True)
.stack()
.reset_index(drop=True, level=1)
.rename('**product**')
)
0 A
0 B
0 C
1 G
1 F
2 C
2 D
2 T
2 R
Name: **product**, dtype: object
cols = df.columns
print (df.join
(
df.pop('**product**')
.str
.strip(',')
.str
.split(',',expand=True)
.stack()
.reset_index(drop=True, level=1)
.rename('**product**')
).reset_index(drop=True)
.reindex_axis(cols,axis=1))
**shop** **product** **location** **time** **count_products**
0 store1 A X 8.30 pm 3
1 store1 B X 8.30 pm 3
2 store1 C X 8.30 pm 3
3 store1 G Y 8.41 pm 2
4 store1 F Y 8.41 pm 2
5 store1 C Z 9.02 pm 4
6 store1 D Z 9.02 pm 4
7 store1 T Z 9.02 pm 4
8 store1 R Z 9.02 pm 4
关于python - 使用 pandas 在 python 中分割文本并相应 append ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40926982/