如何在Python中从现有CSV文件创建数据帧

2024-10-01 15:47:55 发布

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

我试图从python中现有的CSV文件创建dataframe对象,但我面临问题。我试图将CSV文件导入python,但不知道是否成功。

    >>> import os
    >>> userhome = os.path.expanduser('~')
    >>> csvfile= userhome + r'\Desktop\train.csv'
    >>> with open(csvfile, "r") as f:

我写了这些声明之后,它什么也没做。

所以第一个问题-我是否将CSV文件导入python?如果我没有怎么进口?

之后,我如何在python中显示CSV文件中的数据?

我安装了熊猫

Python IDE 3.6.3外壳

enter image description here


Tags: 文件csvcsvfilepath对象importdataframeos
2条回答

相反,使用pandas来读取csv:

import pandas as pd
df = pd.read_csv(csvfile)

有关读取csv的其他选项,请参阅:pandas read csv

如果有人对使用python csv包打开csv文件感兴趣。

import os, csv
some_path = os.path.expanduser('~')
csv_file = some_path + '\path_to_file_from_home_dir\file_name.csv'
# Now let's read the file
with open (csv_file,'r+') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=' ')
    # Confirm that the code works by printing contents of the file 
    for row in csv_reader:
        print(', '.join(row))

你可以阅读更多关于csv reader module

以获得它的全部能力

相关问题 更多 >

    热门问题