【问题标题】:How can I separate text into multiple values in a CSV file using Python? [duplicate]如何使用 Python 将文本分隔为 CSV 文件中的多个值? [复制]
【发布时间】:2021-06-21 21:06:30
【问题描述】:

我想开始处理一些数据进行分析,但我必须将响应分成多个值。目前,每一列包含一个与 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()

【问题讨论】:

    标签: python pandas dataframe csv


    【解决方案1】:

    您需要先使用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
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多