Python Pandas错误:只能使用带字符串值的.str访问器,该访问器在Pandas中使用np.object\dtype

Python Pandas错误:只能使用带字符串值的.str访问器,该访问器在Pandas中使用np.object\dtype,python,pandas,Python,Pandas,我的.txt文件中有如下数据: 029070 ***** 190101010600 270 36 OVC ** 0.0 ** ** 我想从第3列中提取190101,我得到了AttributeError:只能使用带字符串值的.str访问器,它在pandas中使用np.object\dtype,下面是我的python熊猫。下面是我的代码 import pandas as pd import numpy as np import re data = pd.read_csv('dummy.txt',

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

029070 ***** 190101010600 270 36 OVC ** 0.0 ** **
我想从第3列中提取190101,我得到了AttributeError:只能使用带字符串值的.str访问器,它在pandas中使用np.object\dtype,下面是我的python熊猫。下面是我的代码

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])

这里的问题是,当您读取txt文件时,它将“c”强制转换为整数,.str访问器将无法处理非字符串数据类型,您可以通过以下几种方式解决此问题:

选择1 在print语句中将整数转换为字符串

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

0    190101
Name: c, dtype: object
选择2 使用
read\u csv

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

这里的问题是,当您读取txt文件时,它将“c”强制转换为整数,.str访问器将无法处理非字符串数据类型,您可以通过以下几种方式解决此问题:

选择1 在print语句中将整数转换为字符串

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

0    190101
Name: c, dtype: object
选择2 使用
read\u csv

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

这回答了你的问题吗?这回答了你的问题吗?