[英]how to used if else with for loop in pandas data Frame with Column value
我有一個 csv (code.csv) 文件,其中包含一些行中可用的單詞/數據。 在“A”列中,我想在文本文件(data.txt)中計算這些單詞,並希望在 txt 文件(test.txt)中打印計數。 用至少來過 1 次的話。 如果字在 excel 中不可用,請不要打印。 但是計數器打印所有單詞,包括在文本中不可用的單詞,計數為 0。 所以在 for 循環中我想使用 if else 語句。 有人可以幫助我。 我努力了...
`import pandas as pd
df = pd.read_csv("code.csv", delimiter=None, header=None, index_col = False)
df.columns = ['A']
df.dropna(subset = ["A"], inplace=True)
df['A'] = df['A'].astype('string')
with open('data.txt', 'r') as txtfile:
test_string = txtfile.read()
for index, row in df.iterrows():
counter = test_string.count(row['A'])
print(row['A'], ': ' + str(counter), file=open("test.txt", "a"))
`
您可以簡單地在 A 列上為每個單詞應用一個 for 循環,然后在字符串中搜索它,如下所示:
import pandas as pd
df = pd.read_csv('df.csv')
df.columns = ['A']
df.dropna(subset = ["A"], inplace=True)
df['A'] = df['A'].astype('string')
with open('data.txt', 'r') as txtfile:
test_string = txtfile.read()
output = ''
for word in df['A']:
if word in test_string:
print(word, '\t', test_string.count(word))
# words and their count in a string
output += str(word) + ' \t ' + str(test_string.count(word)) + '\n'
# writing to output file
with open('test.txt', 'w') as outputfile:
outputfile.write(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.