從具有特定模式的文字檔案中建立Pandas DataFrame
您需要從具有以下結構的文字檔案中建構Pandas DataFrame :
Alabama[edit] Auburn (Auburn University)[1] Florence (University of North Alabama) Jacksonville (Jacksonville State University)[2] Livingston (University of West Alabama)[2] Montevallo (University of Montevallo)[2] Troy (Troy University)[2] Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3][4] Tuskegee (Tuskegee University)[5]
有「[edit]」的行表示狀態,而有「[edit]」的行表示「[數字]」表示區域。任務是根據這些模式分割文件,並為每個區域名稱重複州名稱。
解決方案:
此過程將產生所需的帶有「州」和「區域名稱」的Pandas DataFrame
範例:
<code class="python">import pandas as pd df = pd.read_csv("filename.txt", sep=";", names=['Region Name']) df.insert(0, 'State', df['Region Name'].str.extract('(.*)\[edit\]', expand=False).ffill()) df['Region Name'] = df['Region Name'].str.replace(r' \(.+$', '') df = df[~df['Region Name'].str.contains('\[edit\]')].reset_index(drop=True) print(df)</code>
輸出:
State Region Name 0 Alabama Auburn 1 Alabama Florence 2 Alabama Jacksonville 3 Alabama Livingston 4 Alabama Montevallo 5 Alabama Troy 6 Alabama Tuscaloosa 7 Alabama Tuskegee 8 Alaska Fairbanks 9 Arizona Flagstaff 10 Arizona Tempe 11 Arizona Tucson
以上是如何從具有特定模式的文本文件創建 Pandas DataFrame?的詳細內容。更多資訊請關注PHP中文網其他相關文章!