【问题标题】:Writing pandas df to csv with if condition使用 if 条件将 pandas df 写入 csv
【发布时间】:2021-03-20 22:47:53
【问题描述】:

我有一个 3 列数据框,我想将满足 if 条件的某些行写入新的 csv。

原始数据框:

应该做我需要的代码块:

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)

我想要的输出:

我实际得到的输出:

写入 csv 有什么问题?谢谢!

【问题讨论】:

    标签: python pandas csv if-statement


    【解决方案1】:

    只需事先对数据帧进行切片,然后再写入。如:

    df_to_write = res[res['Similarity']>0.8]
    
    df_to_write.to_csv('result.csv', index=False)
    

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2015-09-28
        • 2013-05-31
        相关资源
        最近更新 更多