【问题标题】:Splitting text and numbers in dataframe in python在python中分割数据框中的文本和数字
【发布时间】:2021-02-13 23:33:41
【问题描述】:

我有一个列名为“col”的数据框 df 作为第二列,数据如下所示: Dataframe

想在一列中将文本部分与名称“套管尺寸”分开,将数字部分与另一列中的“深度到”分开。 Desired Output

import pandas as pd
import io
from google.colab import files
uploaded = files.upload()
df = pd.read_excel(io.BytesIO(uploaded['Test-Checking.xlsx']))

#Method 1
df2 = pd.DataFrame(data=df, columns=['col'])
df2 = df2.col.str.extract('([a-zA-Z]+)([^a-zA-Z]+)', expand=True)
df2.columns = ['CasingSize', 'DepthTo']
df2

#Method 2
def split_col(x):
  try:
      numb = float(x.split()[0])
      txt = x.split()[1]
  except:
       numb = float(x.split()[1])
       txt = x.split()[0]
    x['col1'] = txt
    x['col2'] = numb
 df2['col1'] = df.col.apply(split_col)
 df2

尝试了两种方法,但都不能正常工作。有人帮我吗?

Google Colab中的代码

Excel文件Attached

【问题讨论】:

    标签: python split


    【解决方案1】:

    试试这个

    首先你需要从你的函数中返回值。然后你可以使用 to_list() 将它们解压到你的列中

    def sample(x):
        b,y=x.split()
        return b,y
    
    temp_df=df2['col'].apply(sample)
    
    df2[['col1','col2']]=pd.DataFrame(temp_df.tolist())
    

    【讨论】:

      【解决方案2】:

      您可以尝试将这些值拆分为一个列表,然后对它们进行排序,以便数字部分在前。然后你可以申请pd.Series 并分配回这两列。

      import pandas as pd
      
      df = pd.DataFrame({'col':["PWT 69.2", '283.5 HWT', '62.9 PWT', '284 HWT']})
      
      df[['Casing Size','DepthTO']] = df['col'].str.split().apply(lambda x: sorted(x)).apply(pd.Series)
      
      print(df)
      

      输出

               col Casing Size DepthTO
      0   PWT 69.2        69.2     PWT
      1  283.5 HWT       283.5     HWT
      2   62.9 PWT        62.9     PWT
      3    284 HWT         284     HWT
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        相关资源
        最近更新 更多