python - 使用 pandas 在 python 中分割文本并相应 append

标签 python pandas numpy split append

我的数据框的一个小样本就是这种格式

**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.splitstack用于为 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/

相关文章:

python - 如何为 tastypie 设置授权 header ?

python - 展平 numpy 数组

python - 如何在 Numpy/Scipy 中获取向量与平面的正交距离?

python - pandas:如何将 groupby 行的子集聚合成一行?

python - 如何使用 Pandas df 在 Python 中水平旋转 csv 表格?

python - Numpy 将 long int 转换为 float 时丢失精度

python - 使用 `sys.getsizeof(Var)` 方法与 `ctypes.sizeof(Var)` 的 python 大小的 ctypes

python - 使用 urllib2 进行 POST 调用而不是 GET

python - 使用QThread的PyQt5 OpenCV WebCam

python-3.x - Pandas 分组并计数,然后按组大小升序对完整数据框进行排序?