the*_*ond 4 python dataframe pandas
我真的不知道如何给出一个好的描述性标题,但这是我的问题。让我们考虑一个 DataFrame df:
col_name
0 Category1
1 item1()
2 item2()
3 Category2
4 item3()
5 item4()
6 item5()
Run Code Online (Sandbox Code Playgroud)
我需要得到这个:
categories items
0 Category1 item1
1 Category1 item2
2 Category2 item3
3 Category2 item4
4 Category2 item5
Run Code Online (Sandbox Code Playgroud)
但categories可能是大陆,items也可能是国家。我知道所有的项目()里面都有一个表达式,所以我可以很容易地提供一个布尔掩码,然后创建一个列表categories:
msk = df[~df['col_name'].str.contains('[^A-Za-z\s]')]['col_name'].tolist()
但是现在,现在我被困住了。你能给我一些建议吗?
让我们startswith找到类别行并创建另一列ffill
df['category']=df.col_name.mask(df.col_name.str.endwith('Category')).ffill()
#df['category']=df.col_name.mask(df.col_name.str.endswith(')')).ffill()
df=df[df.category!=df.col_name]
df
Out[241]:
col_name category
1 item1() Category1
2 item2() Category1
4 item3() Category2
5 item4() Category2
6 item5() Category2
Run Code Online (Sandbox Code Playgroud)