如何删除带有熊猫的占位符



编辑:我放了我想要的结果,似乎我的问题不清楚,对不起!


我需要帮助删除我的占位符,以下是我的问题的更多细节:

假设这是我的数据帧:

import pandas as pd
data = {'product_name': ['laptop', 'printer'],
'price': [1200, 150]
}
df = pd.DataFrame(data)

我创建了一个.txt文件作为介质,用数据帧内容替换占位符。.txt文件如下所示:

placeholder0!
placeholder1!
placeholder2!
placeholder3!

我想使用panda打开.txt文件,用数据帧中的一些值替换占位符,并删除占位符的其余部分。目前我的代码如下所示。

runner = open(('runner.run'),'w')
note = open(('TEMPLATE.TXT'),'r').read()
x = 0
y = len(df.index)
for x in df.index:
if (df.product_name.iloc[x] == 'laptop') :
note = note.replace('placeholder'+str(x)+'!' , 'laptop')
x +=1 
else :
note = note.replace('placeholder'+str(x)+'!', 'xxxx')
x +=1   

#to clean up the rest of the place holder
for x in df.index:
note = note.replace('placeholder'+str(y)+'!', '')
y+=1
output = open('RESULT.TXT', 'w')
output.write(note)
output.close()
runner.close()

结果:

laptop
xxxxx
(empty string)
(empty string)

我想要的结果。TXT:

laptop
xxxxx

我得到的结果是result.TXT是用空字符串替换的占位符(正如代码中所写的,因为我不知道如何删除它们(。我真正想要的是删除所有的占位符。因此,TXT文件将总共有2行,而不是4行(2行用于结果,2行用于空白(你能帮帮我吗?

我希望我能清楚地解释这一点。提前谢谢!

致以亲切的问候。

您可以使用读取占位符文本文件

note = pd.read_csv('yourpathTEMPLATE.txt')

然后使用下面的连接和带掩码的条件。注意,df.join将自动保留df中的索引,并从Note:中消除不匹配的索引

out = df.join(note)
out['product_name'].mask(out['product_name'].ne('laptop'),'xxxx').to_frame()
.to_csv("yourpathRESULT.TXT",index=False)

如果没有更好地查看您的数据,即使不是最高效的方法(再次因为我无法访问您的所有数据(

df.reset_index(inplace = true)
df.rename(columns={'index' : 'holder'}
df = df.loc[df['holder'] != 'placeholder']
df.reset_index('holder, inplace = True)

这应该从根本上让你的索引移动到一列中,然后在df中只搜索不是"占位符"的行,然后将你的索引重置为最初的

最新更新