【发布时间】:2017-08-03 14:30:21
【问题描述】:
大家好,所以我有以下数据框:
WM WH WP LC_REF
0 Tesla League Test DT 17 1C
1 Merc Fandom Tundra DT 17 1C
2 Fellaine Fark '' DT 17 1C
3 SeaWorld '' '' DT 17 1C
4 Rectigy '' '' DT 17 1C
5 Donfae '' '' DT 17 1C
我的代码是这样的:
for num in range(len(df)):
df = df.groupby('LC_REF',sort=False).agg(lambda x: ','.join(x.astype(str).str.upper()).replace(' ','')).stack().rename_axis(('LC_REF','a')).reset_index(name='vals')
产生这个:
LC_REF a vals
0 DT 17 1C WM Tesla,Merc,Fellaine,Seaworld,Rectigy,Donfae
1 DT 17 1C WH League, Fandom, Fark,,,
2 DT 17 1C WP Test,Tundra,,,,
有什么办法可以去掉末尾多余的逗号吗?在我的代码中的某处,因为它正在分组,我希望它删除空白字符串值,所以它看起来像这样:
LC_REF a vals
0 DT 17 1C WM Tesla,Merc,Fellaine,Seaworld,Rectigy,Donfae
1 DT 17 1C WH League, Fandom, Fark
2 DT 17 1C WP Test,Tundra
【问题讨论】:
标签: python python-3.x pandas dataframe