【问题标题】:How to read data from a tsv file in the default data formats which are mixed up and randomly arranged in columns and rows?如何从 tsv 文件中读取默认数据格式的数据,这些数据格式混合并随机排列在列和行中?
【发布时间】:2019-11-17 08:44:31
【问题描述】:

假设我想从 tsv 文件中读取如下所示的数据

4 4.000 one 57.3800 57 4
3 3.000 1 57.3800 seven 3

我是这样做的

df_data = pd.read_csv('./models' + file_path, sep='\t', index_col=False, header=None,
                      skip_blank_lines=False, keep_default_na=False, names=columns)

当我检查数据的格式时

for index, row in df_data.head(2).iterrows():

    for index, key in enumerate(input):

        print(type(row[key]))
        print(row[key])

返回

<type 'float'>
4.0
<type 'float'>
4.0
<type 'str'>
one
<type 'float'>
57.38
<type 'float'>
57.0
<type 'float'>
4.0

<type 'float'>
3.0
<type 'float'>
3.0
<type 'float'>
1.0
<type 'float'>
57.38
<type 'str'>
seven
<type 'float'>
3.0

但它应该看起来像这样

<type 'integer'>
4
<type 'float'>
4.0
<type 'str'>
one
<type 'float'>
57.38
<type 'integer'>
57
<type 'integer'>
4


<type 'integer'>
3
<type 'float'>
3.0
<type 'integer'>
1
<type 'float'>
57.38
<type 'str'>
seven
<type 'integer'>
3

如您所见,我需要保留与读取 tsv 文件之前相同的数据类型。所以我有三种类型——int、string和float。它们混合在一起并随机排列在列和行中。所以没有一行,例如只有整数或只有字符串的列。就像上面的例子一样。因此,不可能铸造例如整列。我只需要默认阅读它们。有什么想法吗?

更新

您对下面显示的解决方案有何看法?如果有人有任何 cmets、提示、改进,我将不胜感激。

def int_or_float(s):
    try:
        return int(s)
    except:
        try:
            return float(s)
        except:
            return s

with open('./models' + file_path) as tsvfile:

    data = csv.reader(tsvfile, delimiter="\t")

    for index, row in enumerate(data):

        row = [int_or_float(el) for el in row]

        for index2, key2 in enumerate(input):

            print(type(row[key2]))
            print(row[key2])

【问题讨论】:

  • 在投反对票时写下原因。

标签: python python-3.x pandas dataframe type-conversion


【解决方案1】:

pd.read_csv() ...

不可能投射例如整列。

您为手头的任务使用了错误的工具。

Pandas 用于结构化列数据。 您的问题定义告诉我们您的数据缺乏结构。

另外,你没有告诉我们你在阅读数据帧后想对它做什么。

对于值的统一处理,您可能会发现它很有帮助 为您读入的每个字符串添加一个无意义的字符串, 例如'value: ',所以 pandas 不会被强制转换为 float 或 int。

csv module 似乎更适合您的需求。

【讨论】:

  • 感谢您的回答。我更新了问题。你能看看我的解决方案并写下你的想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多