gpt4 book ai didi

python - 有条件地填充 pandas 数据框会导致空数据框

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:20 24 4
gpt4 key购买 nike

我正在逐行读取一个大型文本文件,在读取时,我想应用 if 条件,其中需要读取某些代码并将其附加到数据帧中。我有一个工作代码,对于 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('|'))

我想逐行读取与我的代码列表匹配的文件,然后分割分隔符上的数据并从中创建一个数据帧。

最佳答案

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

关于python - 有条件地填充 pandas 数据框会导致空数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56955822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com