Trim 每列值在 pandas

Trim each column values at pandas

我正在使用 pandas 将数据导入数据框后处理 .xls 文件,需要 trim 它们。我有很多专栏。每个数据都以 xxx: 或 yyy: 开头并在一列中 例如:

  1. xxx:abc yyy:def\n
  2. xxx:def yyy:ghi\n
  3. xxx:ghi yyy:jkl\n
  4. ...

我需要 trim 每列的 xxx: 和 yyy:。研究并尝试了一些问题解决方案,但没有奏效。我怎么能trim那个,我需要一个有效的代码。已经谢谢了。

(不必要的字符没有静态长度我只知道它们看起来像停用词。例如:

  1. ['Comp:Apple', 'Product:iPhone', 'Year:2018', '128GB', ...]
  2. ['Comp:Samsung', 'Product:Note', 'Year:2017', '64GB', ...]

我希望新数据集看起来像:

  1. ['Apple', 'iPhone', '2018', '128GB', ...]
  2. ['Samsung', 'Note', '2017', '64GB', ...]

所以我想 trim ('Comp:', 'Product:', 'Year:', ...) 每列的停用词。

您可以为此使用 pd.Series.str.split

import pandas as pd

df = pd.DataFrame([['Comp:Apple', 'Product:iPhone', 'Year:2018', '128GB'],
                   ['Comp:Samsung', 'Product:Note', 'Year:2017', '64GB']],
                  columns=['Comp', 'Product', 'Year', 'Memory'])

for col in ['Comp', 'Product', 'Year']:
    df[col] = df[col].str.split(':').str.get(1)

#       Comp Product  Year Memory
# 0    Apple  iPhone  2018  128GB
# 1  Samsung    Note  2017   64GB