Python中如何去除数组的引号与方括号并转为数值数组?
解决CSV中Polarity列字符串转数值数组的问题
你的问题很明确:CSV里的polarity列存储的是带方括号的字符串(比如[0]),读取后得到的是字符串数组,需要转换成纯整数数组。下面是几种高效的解决方式:
方法一:字符串清洗+类型转换
这是最直接的方式,先去掉字符串两端的方括号,再转成整数:
import pandas as pd # 读取文件 dfx = pd.read_csv('hasil_processing_auto.csv', encoding='unicode_escape') # 处理polarity列:去掉方括号并转为整数 dfx['polarity'] = dfx['polarity'].str.strip('[]').astype(int) # 获取纯数值数组 X = dfx['polarity'].values print(X)
运行后你会得到类似这样的输出:
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1]
方法二:使用apply自定义处理
如果你的数据里polarity字段可能有额外空格(比如[ 1 ]),用apply配合lambda函数更灵活:
dfx['polarity'] = dfx['polarity'].apply(lambda x: int(x.replace('[', '').replace(']', '').strip())) X = dfx['polarity'].values
方法三:读取CSV时直接处理
可以在读取文件阶段就完成转换,省去后续步骤:
def parse_polarity(value): # 移除方括号并转整数 return int(value.strip('[]')) # 读取时指定转换器 dfx = pd.read_csv( 'hasil_processing_auto.csv', encoding='unicode_escape', converters={'polarity': parse_polarity} ) X = dfx['polarity'].values
为什么这些方法有效?
str.strip('[]')会移除字符串首尾的[和],把[0]变成'0'astype(int)或int()将处理后的字符串转换为整数类型- 最终
dfx['polarity'].values返回的是numpy整数数组,打印出来就是你想要的空格分隔格式
内容的提问来源于stack exchange,提问作者alessandro
相关产品推荐
相关产品推荐

