因此,我有一些CSV文件,我正在尝试使用,但其中一些有多个同名列
例如,我可以有这样一个csv:
ID Name a a a b b
1 test1 1 NaN NaN "a" NaN
2 test2 NaN 2 NaN "a" NaN
3 test3 2 3 NaN NaN "b"
4 test4 NaN NaN 4 NaN "b"
加载到pandasis给我这个:
ID Name a a.1 a.2 b b.1
1 test1 1 NaN NaN "a" NaN
2 test2 NaN 2 NaN "a" NaN
3 test3 2 3 NaN NaN "b"
4 test4 NaN NaN 4 NaN "b"
我想做的是将这些同名列合并到一列中(如果有多个值将这些值分开),我的理想输出是
ID Name a b
1 test1 "1" "a"
2 test2 "2" "a"
3 test3 "2;3" "b"
4 test4 "4" "b"
想知道这是否可能
当然,DSM和CTZhu给出了非常简洁的答案,它们利用了Python的许多内置特性,尤其是dataframe。这里有点…[咳嗽]-冗长
这给了我:
您可以在
axis=1
上使用groupby
,并使用类似在这里,您可以使用所需的任何格式运算符,而不是使用
.astype(str)
使用重复的列名可能不是一个好主意,但它会起作用:
相关问题 更多 >
编程相关推荐