python - 无法删除 pandas DataFrame 中的部分字符串

标签 python pandas

我正在使用 KDDCup 来训练神经网络,但我对数据的布局感到相当困惑。当我使用 scikit-learn 数据集函数下载数据集时:

data = datasets.fetch_kddcup99(return_X_y = True, )
df = pd.DataFrame(np.column_stack((data[0], data[1])))

然后运行命令df.head(),它返回以下信息:

  0       1        2      3    4     5      ...     36 37 38 39 40          41
0  0  b'tcp'  b'http'  b'SF'  181  5450     ...      0  0  0  0  0  b'normal.'
1  0  b'tcp'  b'http'  b'SF'  239   486     ...      0  0  0  0  0  b'normal.'
2  0  b'tcp'  b'http'  b'SF'  235  1337     ...      0  0  0  0  0  b'normal.'
3  0  b'tcp'  b'http'  b'SF'  219  1337     ...      0  0  0  0  0  b'normal.'
4  0  b'tcp'  b'http'  b'SF'  217  2032     ...      0  0  0  0  0  b'normal.'

[5 rows x 42 columns]

我试图根据标签的内容将输出类(元素 41)更改为二进制(如果正常则为 0,否则为 1)。现在事实证明这很困难,因为 dtype 是对象,每当我执行 df.str.contains 时,它都会将所有样本(其中一百万个)转换为 NaN。

我认为解决这个问题的方法是将 b ' 替换为空,但我无法成功做到这一点。

我对如何操作这个数据帧感到有点困惑,其中所有列都是 Object 类型,甚至是标量值。

最佳答案

您可以使用编码来移动字符

Python 2 中忽略“b”或“B”前缀;它表明该文字应该成为 Python 3 中的字节文字(例如,当代码自动使用 2to3 转换时)。 “u”或“b”前缀后面可能跟有“r”前缀。 enter link description here

stri="Response from server"    
c.send(stri.encode())

df[41].apply(lambda x: x.decode('utf-8')) 

关于python - 无法删除 pandas DataFrame 中的部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52534147/

相关文章:

python - 在 Python-Scrapy 中执行 Js 的 Selenium 替代品是什么?

python - 如何在使用 Python 插入 MySQL 数据库后获取 "id"?

python - 为什么邻接矩阵的特征值实际上是Textrank中的句子分数

python - Pandas :嵌套数据框

python - 操作/复制数据框( Pandas )并仅维护每个月的最后一天

python - 强制 setup.py 使用我的自定义编译器

python - 尝试在 python 中将 Plotly 图保存到图像文件时出现奇怪的错误?

python - 将字符串转换为 DataFrame 中的 float

python - Pandas Dataframe.describe() : Which kind of standard deviation?

python - Pandas:创建数据框而不按字母顺序自动排序列名