Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas read_csv无法正确加载逗号分隔的csv_Python_Pandas_Csv_Dataframe_Kaggle - Fatal编程技术网

Python Pandas read_csv无法正确加载逗号分隔的csv

Python Pandas read_csv无法正确加载逗号分隔的csv,python,pandas,csv,dataframe,kaggle,Python,Pandas,Csv,Dataframe,Kaggle,现在,我来分析卡格尔的泰坦尼克号挑战。 我的代码是: 但我的理想输出 是: 所以,在我的最后一段代码中 df["Age"].fillna(df.Age.median(), inplace=True) 错误就会发生 --------------------------------------------------------------------------- KeyError Traceback (most recent

现在,我来分析卡格尔的泰坦尼克号挑战。 我的代码是:

但我的理想输出 是:

所以,在我的最后一段代码中

df["Age"].fillna(df.Age.median(), inplace=True)
错误就会发生

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/indexes/base.py in get_loc(self, key, method, tolerance)
   2133             try:
-> 2134                 return self._engine.get_loc(key)
   2135             except KeyError:

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)()

KeyError: 'Age'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-4-9763f0a9951c> in <module>()
----> 1 df["Age"].fillna(df.Age.median(), inplace=True)

/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2057             return self._getitem_multilevel(key)
   2058         else:
-> 2059             return self._getitem_column(key)
   2060 
   2061     def _getitem_column(self, key):

/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_column(self, key)
   2064         # get column
   2065         if self.columns.is_unique:
-> 2066             return self._get_item_cache(key)
   2067 
   2068         # duplicate columns & possible reduce dimensionality

/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/generic.py in _get_item_cache(self, item)
  1384         res = cache.get(item)
   1385         if res is None:
-> 1386             values = self._data.get(item)
   1387             res = self._box_item_values(item, values)
   1388             cache[item] = res

/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/internals.py in get(self, item, fastpath)
   3541 
   3542             if not isnull(item):
-> 3543                 loc = self.items.get_loc(item)
   3544             else:
   3545                 indexer = np.arange(len(self.items))[isnull(self.items)]

/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/indexes/base.py in get_loc(self, key, method, tolerance)
   2134                 return self._engine.get_loc(key)
   2135             except KeyError:
-> 2136                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2137 
   2138         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)()

KeyError: 'Age'
---------------------------------------------------------------------------
KeyError回溯(最近一次呼叫最后一次)
/get_loc中的Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/index/base.py(self、key、method、tolerance)
2133尝试:
->2134返回发动机。获取位置(钥匙)
2135键错误除外:
pandas/index.pyx在pandas.index.IndexEngine.get_loc(pandas/index.c:4433)()
pandas/index.pyx在pandas.index.IndexEngine.get_loc(pandas/index.c:4279)()
pandas.hashtable.PyObjectHashTable.get_项中的pandas/src/hashtable_class_helper.pxi(pandas/hashtable.c:13742)()
pandas.hashtable.PyObjectHashTable.get_项中的pandas/src/hashtable_class_helper.pxi(pandas/hashtable.c:13696)()
关键错误:“年龄”
在处理上述异常期间,发生了另一个异常:
KeyError回溯(最近一次呼叫最后一次)
在()
---->1 df[“Age”].fillna(df.Age.median(),inplace=True)
/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in____getitem_u__(self,key)
2057返回自我。\u获取项目\u多级(键)
2058其他:
->2059返回自我。\u获取项目\u列(键)
2060
2061 def_getitem_列(自身,键):
/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py在_getitem_列中(self,key)
2064#获取列
2065如果self.columns.u是唯一的:
->2066返回自我。\u获取\u项目\u缓存(密钥)
2067
2068#重复列和可能的降维
/Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/generic.py in_get_item_缓存(self,item)
1384 res=cache.get(项)
1385如果res为无:
->1386 values=self.\u data.get(项目)
1387 res=自身。方框\项目\值(项目,值)
1388缓存[项目]=res
/get中的Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/core/internals.py(self、item、fastpath)
3541
3542如果不为空(项目):
->3543 loc=自身物品。获取物品位置(物品)
3544其他:
3545索引器=np.arange(len(self.items))[isnull(self.items)]
/get_loc中的Users/XXXi/anaconda/envs/py36/lib/python3.6/site-packages/pandas/index/base.py(self、key、method、tolerance)
2134返回发动机。获取位置(钥匙)
2135键错误除外:
->2136返回self.\u引擎。获取self.\u loc(self.\u可能\u cast\u索引器(键))
2137
2138 indexer=self.get\u indexer([key],method=method,tolerance=tolerance)
pandas/index.pyx在pandas.index.IndexEngine.get_loc(pandas/index.c:4433)()
pandas/index.pyx在pandas.index.IndexEngine.get_loc(pandas/index.c:4279)()
pandas.hashtable.PyObjectHashTable.get_项中的pandas/src/hashtable_class_helper.pxi(pandas/hashtable.c:13742)()
pandas.hashtable.PyObjectHashTable.get_项中的pandas/src/hashtable_class_helper.pxi(pandas/hashtable.c:13696)()
关键错误:“年龄”
我使用了
sep=”,“
,所以我真的不明白为什么这个代码不能在每个逗号中分开。我该如何解决这个问题

我遵循一个答案,但出现了错误(我不知道为什么)


我的数据是

您的读取csv看起来很好,同一行中的替换似乎引起了麻烦

尝试先将csv原样读入变量df。这样你的代码会更干净

df = pd.read_csv('Desktop/data/train.csv',sep=',')
df['Sex'] = df['Sex'].map( {'female': 1, 'male': 0} )
但您可以完全保留sep参数,因为逗号是标准分隔符

或者,在将文件读入df并使用
inplace=True

df['Sex'].replace({'male': 0, 'female': 1}, inplace=True)
一般建议:

Kaggle网页支持内核部分的脚本共享和评论。 试着看看它,看看如果你被困在某个地方,你如何进行分析:


注意

主要问题是下载数据。如果您在加载和处理Kaggle Titanic数据集时遇到问题,您可以从重新下载CSV并重新运行程序


您可以传递分隔符=',':

df = pd.read_csv("Desktop/data/train.csv", delimiter=',')
print(df.head())

   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   
3            4         1       1   
4            5         0       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1   
4                           Allen, Mr. William Henry    male  35.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
3      0            113803  53.1000  C123        S  
4      0            373450   8.0500   NaN        S  


print(df.columns)

Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
接下来,您可以创建排序映射:

mapping = {'male' : 0, 'female' : 1}
您将调用
pd.Series.replace

df.Sex = df.Sex.replace(mapping)
print(df.Sex)

0    0
1    1
2    1
3    1
4    0
Name: Sex, dtype: int64

你的意思是,df=pd.read_csv(“Desktop/data/train.csv”,sep=',',inplace=True,regex=True)。replace(“男性”,0)。replace(“女性”,1),对吧?但是使用这段代码,我在()--->1df=pd.read_csv(“Desktop/data/train.csv”,sep=',',,inplace=True,regex=True)中得到了一个错误,TypeError Traceback(最近的调用last).replace(“男性”,0).replace(“女性”,1)TypeError:parser_f()得到一个意外的关键字参数“inplace”,我是否误解了您的消息?我编辑了我的原始答案。。。新线路上的清洁是否意味着SDF=pd.read_csv(“Desktop/data/train.csv”,sep=',',,inplace=True,regex=True).替换(“男性”,0).替换(“女性”,1)df.清洁(inplace=True,regex=True)根据熊猫文档
分隔符
只是sep的替代名称:@StefanK从我的经验来看,曾经有过这样的情况,我通过使用它们的组合,或者将其中一个换成另一个来让事情运转起来。我认为它们是互补的,不是替代品。编辑:稍微更改了我的答案。@cᴏʟᴅsᴘᴇᴇᴅ 谢谢你的回答。我跟踪了你的消息,但属性错误发生了。我更新了我的问题,如果你知道什么,请帮助我。@user8385498运行我所有的代码都德。你只遵循了映射部分。我精确地遵循了你的代码,但同样的错误也发生了(我在代码之前发现了一个错误)我更新了我的问题,如果你发现了一些错误,请告诉我。