【问题标题】:Python: Split List into 2 Sublists by tabseperating elementsPython:通过制表符分隔元素将列表拆分为 2 个子列表
【发布时间】:2019-04-08 23:37:18
【问题描述】:

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

背景: 我想将由制表符分隔的.txt 文件读入 Pandas DataFrame。这些文件看起来像:

第 1 列 \t 123
第 2 列 \t
Column3 \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

【问题讨论】:

标签: python list


【解决方案1】:

如果我理解正确,您可以将read_csv 给您的数据帧转置为delimiter='\t'

演示:

>>> from io import StringIO           
>>> import pandas as pd                                                         
>>>                                                                             
>>> file = StringIO('''Column1\t123 
...: Column2\t 
...: Column3\ttext''')                                                      
>>>                                                                             
>>> df = pd.read_csv(file, delimiter='\t', index_col=0, header=None).T                                                                
>>> df                                                                          
>>>
0 Column1 Column2 Column3
1     123     NaN    text

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

【讨论】:

    【解决方案2】:

    您可以像这样将文件读入数据框:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2015-12-14
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多