ある時点でオンラインで不動産リストをスナップショットしている〜40個のcsvファイルがあります。私はこれらを1つのcsvファイルに統合しようとしていますが、同時に不動産のリスティングがいつ投稿されるのか、それらが取り下げられるのかを指定します(つまりリスティングが新しい場合はcsvファイルの最後に追加します「最後に見た」列を最新の日付で更新する前に存在し、別の列に掲載された日付は保持していた)。ループ内にパンダデータフレームを変更して追加する
私は私が助けを求めたい二つのものがあります。
1)私は書かれているループは「初期」のIDを見て、更新するために、「新しく追加された」リストを検索しませんが、彼らの " (つまり、リスティングが最初のバッチにない場合は、以前のcsvファイルが統合マスターに追加されていても、すべて「新規」とみなされます) - データフレームを更新するにはどうすればよいですか新しいcsvファイルを最新のマスタデータフレームと比較しますか?
2)私のコードは非常に効率が悪いようですが、実行には20分かかります - 効率を上げることはできますか?
これまでの私のコード:
import pandas as pd
from datetime import timedelta, date
import os
def daterange(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
#Define what date range to consolidate
start_date = date(2017, 8, 1)
end_date = date.today()
#Create a starting dataframe with the first csv file and change the "hash_id" to string to prepare dataframe for insertions using this as the unique identifier for each listing
master_df = pd.read_csv("real_estate(" + start_date.strftime("%d-%m-%Y") + ").csv")
master_df = master_df.assign(last_seen=master_df['date'])
master_df['hash_id'] = master_df['hash_id'].astype(str)
#Loop through all CSV files for the time period listed, if listing is already in dataframe then update the "last seen" with the newer date, otherwise add the listing as a new row to the master dataframe
for single_date in daterange(start_date, end_date):
file_path = "real_estate(" + single_date.strftime("%d-%m-%Y") + ").csv"
print(single_date.strftime("%d-%m-%Y"))
if os.path.isfile(file_path) is True and os.path.getsize(file_path) > 1:
temp_df = pd.read_csv(file_path)
temp_df = temp_df.assign(last_seen=temp_df['date'])
for index, row in temp_df.iterrows():
hash_id = str(row['hash_id'])
if master_df['hash_id'].str.contains(hash_id).any():
master_df.loc[master_df['hash_id'] == hash_id, 'last_seen'] = row['date']
else:
master_df.loc[len(master_df)] = row
#write the consolidated dataframe to CSV
master_df.to_csv("master_file.csv")
ありがとう、本当に優雅なソリューションのようです。言いたいことを忘れてしまったことにお詫び申し上げますが、最初に見たときを示す列「日付」もあります。投稿のオンライン期間を計算したいと思います。同時に、各投稿の「最初に見た」と「最後に見た」を保持するようにソリューションを適応させる可能性はありますか? – Svarto
hash_idの複製を削除した後、日付列はデータが最初にリストされたときのようになります。 「最初に見た」と「最後に見た」との違いは、列の日付とlast_seenの違いだけです。または私はここに何かを逃していますか? –
完璧に働いた、ありがとう! – Svarto