python - 如何使用 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()
解决方案
您需要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
推荐阅读
- java - Android Camera App 使用 CameraX 将图像保存为 YUV_420_888 格式
- alert - 在 ionic5 中创建通用的可重用警报
- python - 内存错误python
- reactjs - 如何在反应和打字稿中为 forwardRef 扩展引用类型以允许多个引用
- tensorflow - 使用 tensorflow 2.0 执行线性回归
- php - 无法通过在 Wordpress 中使用 php ajax 从 url 获取数据
- mysql - 无法将mysql的字符集从utf8mb4更新为utf8
- liquibase - 如何在 Liquibase 中多次执行单个数据库脚本?
- ruby-on-rails - kaminari 不适用于从 gem 加载的模型
- javascript - 过滤两个日期之间的 JSON 数据