首页 > 解决方案 > 如何使用 Python 将文本分隔为 CSV 文件中的多个值?

问题描述

我想开始处理一些数据进行分析,但我必须将响应分成多个值。目前,每一列包含一个与 3 个响应组合的值,同意:#score,不同意:#score,既不同意也不反对。我想将列中的响应分成单独的值,以创建可视化分析。我需要包含正则表达式来执行此操作吗?

样本数据集

到目前为止,我拥有的代码只是用我计划使用的一些库加载数据:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def load_data():

    # importing datasets
    df=pd.read_csv('dataset.csv')
    
    return df
load_data().head()

标签: pythonpandasdataframecsv

解决方案


您需要str.split(';')先将值拆分为多列。然后对于每个列值,再次使用拆分字符串,str.split(':')但要使用[-1]它的一部分。

这是你如何做到的。

import pandas as pd
df = pd.DataFrame({'username':['Dragonfly','SpeedHawk','EagleEye'],
                   'Question1':['Comfortable:64;Neither comfortable nor uncomfortable:36',
                                'Comfortable:0;Neither comfortable nor uncomfortable:100',
                                'Comfortable:10;Neither comfortable nor uncomfortable:90'],
                   'Question2':['Agree:46;Disagree:13;Neither agree nor disagree:41',
                               'Agree:96;Disagree:0;Neither agree nor disagree:4',
                               'Agree:90;Disagree:5;Neither agree nor disagree:5']})

df[['Q1_Comfortable','Q1_Neutral']] = df['Question1'].str.split(';',expand=True)
df[['Q2_Agree','Q2_Disagree','Q2_Neutral']] = df['Question2'].str.split(';',expand=True)

df.drop(columns=['Question1','Question2'],inplace=True)
for col in df.columns[1:]:
    df[col] = df[col].str.split(':').str[-1]

print (df)

其输出将是:

    username Q1_Comfortable Q1_Neutral Q2_Agree Q2_Disagree Q2_Neutral
0  Dragonfly             64         36       46          13         41
1  SpeedHawk              0        100       96           0          4
2   EagleEye             10         90       90           5          5

推荐阅读