Tomito
Tomito

Reputation: 35

Writing pandas df to csv with if condition

I have a 3-column dataframe and I want to write certain rows that meet if condition into a new csv.

Original dataframe:enter image description here

Chunk of the code which is supposed to do what I need:

res = pd.DataFrame.from_dict(d_out, orient='index')

res.columns = ['id', 'id2', 'Similarity']

for index, row in res.iterrows():
    if row[2] > 0.8:
        row.to_csv('result.csv', index=False)

The output I want:enter image description here

The output I actually get:enter image description here

What am doing wrong in writing to csv? Thanks!

Upvotes: 0

Views: 1682

Answers (2)

user15410836
user15410836

Reputation:

import pandas as pd


res = pd.DataFrame.from_dict(d_out, orient="columns")
res.columns = ['id', 'id2', 'Similarity']

final_row = []
for index, row in res.iterrows():
    if row['Similarity'] > 0.8:
        final_row.append(index)

res.iloc[final_row].to_csv("result.csv", index=False)

Upvotes: 0

leed
leed

Reputation: 312

Just slice the dataframe beforehand and then write it. As in:

df_to_write = res[res['Similarity']>0.8]

df_to_write.to_csv('result.csv', index=False)

Upvotes: 3

Related Questions