【问题标题】:I cannot import CSV file?我无法导入 CSV 文件?
【发布时间】:2019-05-12 15:23:40
【问题描述】:

我对 python 和一般编程完全陌生。

我想做著名的“泰坦尼克号”数据科学项目,但我无法读取 CSV 文件,尽管我上传了它们。我使用 Jupyter 和 Python 3。

我多次下载了所有 CSV 文件。

# data analysis and wrangling
import pandas                as pd
import numpy                 as np
import random                as rnd

# visualization
import seaborn               as sns
import matplotlib.pyplot     as plt
%matplotlib inline

# machine learning
from sklearn.linear_model  import LogisticRegression
from sklearn.svm           import SVC, LinearSVC
from sklearn.ensemble      import RandomForestClassifier
from sklearn.neighbors     import KNeighborsClassifier
from sklearn.naive_bayes   import GaussianNB
from sklearn.linear_model  import Perceptron
from sklearn.linear_model  import SGDClassifier
from sklearn.tree          import DecisionTreeClassifier



##Acquire data

train_df   = pd.read_csv('../input/train.csv')    #here I get the error
test_df    = pd.read_csv('../input/test.csv')
combine    = [train_df, test_df]

错误:FileNotFoundError

我应该更改目录路径吗?但如果是这样,以什么方式?

【问题讨论】:

  • 是的,您应该更改路径。请显示目录树的相关部分(Python 脚本在哪里,.csv 文件在哪里)。
  • csv 文件在 Titanic 文件夹中,那你为什么要使用 ../input/
  • 为了安全起见,要么使用 csv 的完整路径,要么使用os.path.join 创建你的路径@DaNickste,在下面查看我的答案 :)
  • C:\Users\myname /Desktop 我在原来的帖子中也做了截图
  • 相对路径是从工作目录而不是脚本位置解析的。

标签: python csv data-science


【解决方案1】:

为了安全起见,请在两个文件中提供 csv 文件的 full 路径以加载您的数据帧

train_df   = pd.read_csv('<path_to_csv>/train.csv')  
test_df    = pd.read_csv('<path_to_csv>/test.csv')
combine    = [train_df, test_df]

或者如果你知道csv文件的目录,使用os.path.join创建完整路径

import os

folder = "<path_to_csv>"

#Full path of csv files
train_path = os.path.join(folder, 'train.csv')
test_path = os.path.join(folder, 'test.csv')

#Use full path to open csv file
train_df = pd.read_csv(train_path)  
test_df = pd.read_csv(test_path)
combine = [train_df, test_df]

另外,如果您知道 csv 文件与运行脚本的位置相同,您也可以使用 os.path.dirname(__file__) 获取当前文件夹。

【讨论】:

  • os.dirname(__file__) 如果您知道 CSV 在脚本旁边,会很方便
  • 很棒的提示!我将它添加到@MadPhysicist 的答案中,如果它看起来不错,请看一下并考虑投票:) PS 它是os.path.dirname(__file__) :)
  • getcwd 可以在外部更改:您可以从任何地方运行脚本。脚本的位置大概不会。
  • 你是对的@MadPhysicist 更新了我的答案来解决这个问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2014-05-23
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
相关资源
最近更新 更多