Python 从列数据框中的不同值创建索引/行
我真的不知道如何给出一个好的描述性标题,但我的问题是。让我们考虑一个数据文件<代码> df>代码>:Python 从列数据框中的不同值创建索引/行,python,pandas,dataframe,Python,Pandas,Dataframe,我真的不知道如何给出一个好的描述性标题,但我的问题是。让我们考虑一个数据文件 df>代码>: col_name 0 Category1 1 item1() 2 item2() 3 Category2 4 item3() 5 item4() 6 item5() 我需要得到这个: categories items 0 Category1 item1 1 Category1 item2 2 C
col_name
0 Category1
1 item1()
2 item2()
3 Category2
4 item3()
5 item4()
6 item5()
我需要得到这个:
categories items
0 Category1 item1
1 Category1 item2
2 Category2 item3
3 Category2 item4
4 Category2 item5
但是类别
可以是大陆,项目
可以是国家。
我知道所有项目都有()
,里面有一个表达式,因此我可以很容易地提供一个布尔掩码,然后创建一个类别列表,其中包含:
msk=df[~df['col\u name'].str.contains(“[^A-Za-z\s]”)]['col\u 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
这里有必要指定如何区分非类别或类别值。在这些解决方案中,如果数据中有(
),则测试值,然后用缺少的值替换这些值并向前填充,然后用原始掩码替换()
,最后一次过滤:
m = df['col_name'].str.contains('(', regex=False)
df['categories'] = df['col_name'].mask(m).ffill()
df['items'] = df.pop('col_name').str.replace('[\(\)]', '')
df = df[m]
print (df)
categories items
1 Category1 item1
2 Category1 item2
4 Category2 item3
5 Category2 item4
6 Category2 item5
通过以下方式更改添加数字的掩码的解决方案:
m = df['col_name'].str.contains('[^A-Za-z0-9\s]')
df['categories'] = df['col_name'].mask(m).ffill()
df['items'] = df.pop('col_name').str.replace('[\()]', '')
df = df[m]
print (df)
categories items
1 Category1 item1
2 Category1 item2
4 Category2 item3
5 Category2 item4
6 Category2 item5
只有当他的大陆都以类似的子串开始时,这才有效!我怀疑情况会是这样!@Mit检查标记df['category']=df.col\u name.mask(df.col\u name.str.endswith(')).ffill()