我有这样的事情:
df =
col1 col2 col3
0 B C A
1 E D G
2 NaN F B编辑:我需要将它转换为:
result =
Name location
0 B col1,col2
1 C col1
2 A col1
3 E col2
4 D col2
5 G col2
6 F col3本质上是得到一个“位置”,告诉我“名称”在哪个列中。提前谢谢你。
发布于 2021-09-21 12:33:17
或者使用stack()的替代方案
new = df.stack().reset_index().drop('level_0',axis=1).dropna()
new.columns = ['name','location']指纹:
name location
0 col1 B
1 col2 C
2 col3 A
3 col1 E
4 col2 D
5 col3 G
6 col2 F编辑:
要获得更新的输出,可以使用groupby和join()
new.groupby('location').agg({'name':lambda x: ', '.join(list(x))}).reset_index()这给了你:
location name
0 A col3
1 B col1, col3
2 C col2
3 D col2
4 E col1
5 F col2
6 G col3发布于 2021-09-21 12:27:11
试试melt和dropna
>>> df.melt(var_name='location').dropna().groupby('value', sort=False, as_index=False).agg(', '.join)
value location
0 B col1, col3
1 E col1
2 C col2
3 D col2
4 F col2
5 A col3
6 G col3
>>> 还有groupby和agg。
发布于 2021-09-21 12:41:16
尝试使用melt将columns转换为rows。并给rows一个column名称。
然后dropna删除rows中的NaN值。
df = df.melt(var_name="location", value_name="Name").dropna()https://stackoverflow.com/questions/69268828
复制相似问题