假設我有一張看起來像這樣的表格:
---------------------------------- ------------------------------------- ----------------------------------
| ExperienceModifier|ApplicationId | ExperienceModifier|RatingModifierId | ExperienceModifier|ActionResults |
---------------------------------- ------------------------------------- ----------------------------------
| | | |
---------------------------------- ------------------------------------- ----------------------------------
我想抓取所有以“ExperienceModifier”開頭的列,并將其結果填充到它自己的資料框中。我將如何使用 pandas 完成此任務?
uj5u.com熱心網友回復:
你可以試試pandas.DataFrame.filter
df.filter(like='ExperienceModifier')
如果要獲取僅包含ExperienceModifier開頭的列。
df.filter(regex='^ExperienceModifier')
uj5u.com熱心網友回復:
Ynjxsjmh 的答案將獲得所有包含“ExperienceModifier”的列。如果您確實想要以該字串開頭的列,而不是僅僅包含它,您可以執行new_df = df[[col for col in df.columns if col[:18] == 'ExperienceModifier']]. 如果所有所需的列都|在“ExperienceModifier”之后,您也可以這樣做new_df = df[[col for col in df.columns if col.split('|')[0] == 'ExperienceModifier']]。所有這些都將創建資料框的視圖。如果你想要一個完全獨立的資料框,你應該復制它,像這樣:new_df = df[[col for col in df.columns if col.split('|')[0] == 'ExperienceModifier']].copy(). |您可能還希望通過拆分列名而不是創建單獨的資料框來創建多索引。
uj5u.com熱心網友回復:
接受的答案很容易完成作業,但我仍然附上我的“手工制作版本”:
import pandas as pd
import numpy as np
import re
lst = [[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]]
column_names = [['ExperienceModifier|ApplicationId', 'ExperienceModifier|RatingModifierId', 'ExperienceModifier|ActionResults','OtherName|ActionResults']]
data = pd.DataFrame(lst, columns = column_names)
data
old_and_dropped_dataframes = []
new_dataframes=[]
for i in np.arange(0,len(column_names[0])):
column_names[0][i].split("|")
splits=re.findall(r"[\w'] ", column_names[0][i])
if "ExperienceModifier" in splits:
new_dataframe = data.iloc[:,[i]]
new_dataframes.append(new_dataframe)
else:
old_and_dropped_dataframe = data.iloc[:,[i]]
old_and_dropped_dataframes.append(old_and_dropped_dataframe)
ExperienceModifier_dataframe = pd.concat(new_dataframes,axis=1)
ExperienceModifier_dataframe
OtherNames_dataframe = pd.concat(old_and_dropped_dataframes,axis=1)
OtherNames_dataframe
此腳本從初始資料幀開始創建兩個新資料幀:一個包含名稱以ExperienceModifier開頭的列,另一個包含不以ExperienceModifier開頭的列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/458753.html
上一篇:將大資料框拆分為更小的子集列
下一篇:從串列中創建N個資料框
