【问题标题】:Pandas error: Can only use .str accessor with string values, which use np.object_ dtype in pandasPandas 错误:只能将 .str 访问器与字符串值一起使用,后者在 pandas 中使用 np.object_ dtype
【发布时间】:2018-08-04 03:36:59
【问题描述】:

我的 .txt 文件中有如下数据:

029070 ***** 190101010600 270 36 OVC ** 0.0 ** **

我想从第 3 列中提取 190101,我得到 AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandasbelow is my python pandas。下面是我的代码

import pandas as pd
import numpy as np
import re

data = pd.read_csv('dummy.txt', sep=" ", low_memory=False, header=None)
data.columns = ["a", "b", "c","d","e","f","g","h","i","j"]

print(data.c.str[0:6])

【问题讨论】:

标签: python pandas


【解决方案1】:

这里的问题是,当您读取 txt 文件时,它会将“c”转换为整数,并且 .str 访问器不适用于非字符串 dtype,您可以通过以下几种方式解决此问题:

选项 1

在打印语句中将整数转换为字符串。

print(data.c.astype(str).str[0:6])

0    190101
Name: c, dtype: object

选项 2

read_csv 中使用dtype 参数将字符串转换为数据帧

data = pd.read_csv(txtfile, sep=' ', header=None, dtype={2:'str'})
data.columns = list('abcdefghij')
print(data.c.str[0:6]

0    190101
Name: c, dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 2017-06-01
    • 2018-12-22
    • 2021-03-18
    • 2020-03-27
    • 2022-01-01
    相关资源
    最近更新 更多