gpt4 book ai didi

python - 如果所有值都在同一列中,如何从 csv 文件读取数据?

转载 作者:行者123 更新时间:2023-11-30 22:32:21 25 4
gpt4 key购买 nike

我有一个以下格式的 csv 文件:

"age","job","marital","education","default","balance","housing","loan"
58,"management","married","tertiary","no",2143,"yes","no"
44,"technician","single","secondary","no",29,"yes","no"

但是,它们不是由制表符(不同的列)分隔,而是全部位于同一第一列中。当我尝试使用 pandas 阅读此内容时,输出给出同一列表中的所有值,而不是列表列表。

我的代码:

dataframe = pd.read_csv("marketing-data.csv", header = 0, sep= ",")
dataset = dataframe.values
print(dataset)

输出:

[[58 'management' 'married' ..., 2143 'yes' 'no']
[44 'technician' 'single' ..., 29 'yes' 'no']]

我需要什么:

[[58, 'management', 'married', ..., 2143, 'yes', 'no']
[44 ,'technician', 'single', ..., 29, 'yes', 'no']]

我缺少什么?

最佳答案

我认为您对不显示逗号的 print() 输出感到困惑。

演示:

In [1]: df = pd.read_csv(filename)

Pandas 表示:

In [2]: df
Out[2]:
age job marital education default balance housing loan
0 58 management married tertiary no 2143 yes no
1 44 technician single secondary no 29 yes no

Numpy 表示:

In [3]: df.values
Out[3]:
array([[58, 'management', 'married', 'tertiary', 'no', 2143, 'yes', 'no'],
[44, 'technician', 'single', 'secondary', 'no', 29, 'yes', 'no']], dtype=object)

Numpy string 表示(print(numpy_array) 的结果):

In [4]: print(df.values)
[[58 'management' 'married' 'tertiary' 'no' 2143 'yes' 'no']
[44 'technician' 'single' 'secondary' 'no' 29 'yes' 'no']]

结论:您的 CSV 文件已正确解析。

关于python - 如果所有值都在同一列中,如何从 csv 文件读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com