在pandas DF中选择列

2024-09-28 22:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的数据,我正在尝试访问一个列。直到昨天,它还运转良好,但现在我不确定我是否做错了什么:

    DISTRICT;CPE;EQUIPMENT,NR_EQUIPM
0   47;CASTELO BRANCO;17520091VM;101                                                                                                                                                                                                     
1   48;CASTELO BRANCO;17520103VV;160                                                                                                                                                                                                     
2   49;CASTELO BRANCO;17520103VV;160

当我尝试这个时,它会给我一个错误:

df = pd.read_csv(archiv, sep=",")   
df['EQUIPMENT']  

错误:

KeyError: 'EQUIPMENT'

我也在尝试,但也不起作用:

df.EQUIPMENT

错误:

AttributeError: 'DataFrame' object has no attribute 'EQUIPMENT'

顺便说一句,我正在使用:

Python 2.7.12 |Anaconda 4.1.1 (32-bit)| (default, Jun 29 2016, 11:42:13) [MSC v.1500 32 bit (Intel)]

你知道吗?你知道吗


Tags: csv数据dfread错误bitnrpd
1条回答
网友
1楼 · 发布于 2024-09-28 22:17:24

您需要将sep更改为;,因为分隔符在csv中更改:

df = pd.read_csv(archiv, sep=";") 

如果选中列的最后一个分隔符,则有,,因此可以使用两个分隔符-;,,但需要添加参数engine='python',因为警告:

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'. for index, row in df.iterrows():

样品:

import pandas as pd
import io

temp=u"""DISTRICT;CPE;EQUIPMENT,NR_EQUIPM
47;CASTELO BRANCO;17520091VM;101
48;CASTELO BRANCO;17520103VV;160
49;CASTELO BRANCO;17520103VV;160"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="[;,]", engine='python')

print (df)
   DISTRICT             CPE   EQUIPMENT  NR_EQUIPM
0        47  CASTELO BRANCO  17520091VM        101
1        48  CASTELO BRANCO  17520103VV        160
2        49  CASTELO BRANCO  17520103VV        160

相关问题 更多 >