我正在尝试读取一个 csv 文件,该文件不包含标题行,并且包含不确定数量的列和 pandas。
我已经搜索了如何解决这个问题,但是我找到的所有答案都要求我已经知道(通过打开文件进行搜索)列可以拥有的最大数量并创建一个names=
属性上read_csv
函数,像这样:
names = ["a", "b", "c", "d"]
table = pandas.read_csv('freqs.tsv', header=None, sep='\t+', names=names)
我的问题是,有没有可能的方法来做到这一点不知道最大列数?为了脚本将来的可重用性,我想概括一下是否可能。
这是我用来运行一些测试的示例文本文件:
mathematics 1.548438245 1.4661764369999999 1.429891562
english 1.237816576 1.043399455
physics 2.415563662 11.165497484000001 5.954598265 7.853732762999999 7.929835858
drama 2.0439384830000003 9.81210385 5.068332477 8.579349377 5.962282599999999
health 1.557941553 1.222267933
science 1.550193476
gym 1.240610831 1.149375944 1.899408195 1.3713249980000002
谢谢
我得到以下输出
|
0 |
1 |
2 |
3 |
4 |
mathematics |
1.54844 |
1.46618 |
1.42989 |
nan |
nan |
english |
1.23782 |
1.0434 |
nan |
nan |
nan |
physics |
2.41556 |
11.1655 |
5.9546 |
7.85373 |
7.92984 |
drama |
2.04394 |
9.8121 |
5.06833 |
8.57935 |
5.96228 |
health |
1.55794 |
1.22227 |
nan |
nan |
nan |
science |
1.55019 |
nan |
nan |
nan |
nan |
gym |
1.24061 |
1.14938 |
1.89941 |
1.37132 |
nan |
通过写:
import pandas as pd
# Assume your data is in test.txt in the current working directory
f = open("test.txt", "r")
# This assumes your spacing is arbitrary
data = [line.split() for line in f]
data = {line[0] : [float(item) for item in line[1:]] for line in data}
# The orient = "index" allows us to handle differing lengths of entries
df = pd.DataFrame.from_dict(data, orient="index")
# this just provides the above table for printing in StackOverflow
print(df.to_markdown())
请注意,我假设文件中的间距是任意的,因此我们不需要跟踪哪些列是空的,我们只需按空格分割并保留值即可。
另请注意nan
表示“不是数字”,如果您有不同长度的行,则您应该在数据框中看到它。
最后,如果您希望主题作为列,请使用df = df.transpose()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)