有条件地填充熊猫数据框将导致空数据框

时间:2019-07-09 15:19:26

标签: python python-3.x if-statement text-files

我正在逐行读取大型文本文件,并且在读取时,如果条件需要读取某些代码并将其附加到数据帧中,我想应用if。我有一个工作代码,对于如果tag ='ABC-1234'的1个代码来说效果很好,那么它就可以工作,但是当我输入更多代码时,最终会得到空数据框。我有100多个代码,现在只想阅读这些行。如果有人提出解决我所面临问题的更好方法,我将不胜感激。下面是工作代码示例。

import pandas as pd
filename ="C:/Users/abcd/Downloads/abcd-xyz-433.txt"
filename =filename
code= pd.read_excel('C:/Users/abcd/Downloads/xyz_codes.xlsx')
code_list=code['codes'].tolist()

with open(filename, 'r') as f:
    sample =[]
    for line in f:
        tag=line[:45].split('|')[5]
        if tag == 'AB-C711':                         #This works
            sample.append(line.split('|')) 

print('Everything in the list is read') 

有两种不同的陈述,我试图使其发挥作用。但是我最终得到空的数据框。 Code_list是从excel文件中的代码列创建的列表。

if tag == ('AB-C711', 'AB-D702'):            #This doesnt work
            sample.append(line.split('|')) 

if tag == code_list:                         #This doesnt work
            sample.append(line.split('|'))  

我想逐行读取与代码列表匹配的文件,然后在定界符上分割数据并从中创建数据框。

1 个答案:

答案 0 :(得分:0)

import pandas as pd
filename ="C:/Users/vgowda/Downloads/abcd-xyz-433.txt"
filename =filename
code= pd.read_excel('C:/Users/Downloads/abc_codes.xlsx')
code_list=code['codes'].tolist()

with open(filename, 'r') as f:
    sample =[]
    for line in f:
        tag=line[:45].split('|')[5]
        if tag in code_list:        # this works
#         if tag == 'KV-C901':
            sample.append(line.split('|')) 

print('arrays are appended and ready to create a dataframe out of an array') 
相关问题