Python:通过tabseparating元素将列表拆分为2个子列表

Python:通过tabseparating元素将列表拆分为2个子列表,python,list,Python,List,问题: 如何将列表拆分为两个子列表,其中元素由元素中的选项卡分隔 上下文: 我想将一个由制表符分隔的.txt文件读入数据框。这些文件看起来像: 第1列\t 123 第2列\t 第3列\t文本 这意味着每行有一列,后面跟着一个选项卡,然后是该列的一个值(有时没有值) 我的想法是读取文件并将每一行保存为列表的一个元素,然后将列表分成两部分,将选项卡前面的第一部分作为一个列表,将选项卡后面的第二部分作为另一个列表。然后从那里构建我的数据帧 for file in txt_files: #iterat

问题: 如何将列表拆分为两个子列表,其中元素由元素中的选项卡分隔

上下文: 我想将一个由制表符分隔的
.txt
文件读入数据框。这些文件看起来像:

第1列\t 123
第2列\t
第3列\t文本

这意味着每行有一列,后面跟着一个选项卡,然后是该列的一个值(有时没有值)

我的想法是读取文件并将每一行保存为列表的一个元素,然后将列表分成两部分,将选项卡前面的第一部分作为一个列表,将选项卡后面的第二部分作为另一个列表。然后从那里构建我的数据帧

for file in txt_files:  #iterate over all files
  f = open(file)        #open each file individually
  lines = f.readlines() #read each line as an element into a list 
  f.close()

#make sublists columns and values

您可以将文件读入如下数据框:

import pandas as pd

# Empty list to store dataframe rows
df_rows = []

# Read all text files
for tf in text_files:
    # For each file
    with open(tf) as f:
        # Empty dictionary to store column names and values
        df_dict = {}

        # For each line
        for line in f:
            # Split by tab
            k, v = line.split('\t')

            # Column name as key, value as  value
            df_dict[k] = v

        # Add the dictionary to list
        df_rows.append(df_dict)

# Read the list of dictionaries as a dataframe
df = pd.DataFrame(df_rows)

# Preview dataframe
df.head()

您可以将文件读入如下数据框:

import pandas as pd

# Empty list to store dataframe rows
df_rows = []

# Read all text files
for tf in text_files:
    # For each file
    with open(tf) as f:
        # Empty dictionary to store column names and values
        df_dict = {}

        # For each line
        for line in f:
            # Split by tab
            k, v = line.split('\t')

            # Column name as key, value as  value
            df_dict[k] = v

        # Add the dictionary to list
        df_rows.append(df_dict)

# Read the list of dictionaries as a dataframe
df = pd.DataFrame(df_rows)

# Preview dataframe
df.head()

如果我理解正确,您只需将数据帧转置
read\u csv
将为您提供
delimiter='\t'

演示:


(如果您的分隔符真的是
'\t'
,那么请使用
分隔符='\t'
engine='python'
)。

如果我理解正确,您可以将
读取的数据框转置为
分隔符='\t'

演示:


(如果您的分隔符确实是
'\t'
,则使用
分隔符='\t'
引擎='python'
).

数据框应该是什么样子?分隔符
'\t'
还是
'\t'
?您可能想跳过循环,只使用
读取csv
:数据框应该是什么样子?分隔符
'\t'
'\t'
?您可能想跳过循环,只使用它
读取\u csv