从具有特定模式的文本文件创建 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中文网其他相关文章!