如何拆分数据帧中的列值

2024-06-16 10:06:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在数据帧中拆分具有字符串的单个列而不创建更多列。去掉括号。你知道吗

例如,两行如下所示:

df = pd.DataFrame({'Ala Carte':'||LA1: 53565 \nCH2: 54565', 
                'Blistex':'|Cust: 65565\nCarrier: 2565|', 
                'Dermatology':'||RTR1\n65331\n\nRTR2\n65331'})

我想让输出数据框看起来像这样,其中信息列是一个字符串:

Customer      Information

Ala Carte     LA1: 53565 
              CH2: 54565

Blistex       Cust: 65565
              Carrier: 2565

Dermatology   RTR1: 65331
              RTR2: 65331

在同一列中获取信息


Tags: 数据字符串dataframedf括号pdcustala
2条回答

这应该做到:

import pandas as pd

### CREATE DATAFRAME
df = pd.DataFrame({'name' : ['Ala Carte', 'Blistex'],
                   'information': ['||LA1: 53565 \nCH2: 54565',
                                   '|Cust: 65565\nCarrier: 2565|']
                  })

### SPLIT COLUMNS INTO A LIST 
df['information'] = df['information'].apply(lambda x: x.replace("|", "").split("\n"))

### EXPLODE THE COLUMN
df.explode('information')

我决定将“\n”替换为“| |”,以此来分隔这两个不同的值。使用此定义组合两列

def combine_with_nan(x, cols):
    combined=''
    for column in cols:
        try:
            np.isnan(x[column])
            Temp = ''
        except:
            Temp = x[column]
        combined= combined + ' || ' + Temp

    return combined 
cols=['Columns you want to merge']
practicedf = practicedf.apply(combine_with_nan, axis=1,args=(cols,)).to_frame().replace(r"\\n"," || ", regex=True)

相关问题 更多 >