pandas.DataFrame.groupby
与axis=1
OP没有明确列名的一般特征。请阅读各种选项,确定哪个对您的特定情况更合适。
可调用
版本#1
假设您的列前缀是单个字符...
from operator import itemgetter
df.groupby(itemgetter(0), axis=1).sum()
C T
0 62 33
1 145 99
当您将一个callable
传递给pandas.DataFrame.groupby
时,它会将该可调用对象映射到索引(如果axis=1
则为列),并将唯一结果作为分组键。
callable
版本#2:自定义函数
稍微有些复杂,但应该对不止单个字符前缀具有鲁棒性。此外,没有使用任何导入。
def yield_while_alpha(x):
it = iter(x)
y = next(it)
while y.isalpha():
yield y
y = next(it)
def get_prefix(x):
return ''.join(yield_while_alpha(x))
df.groupby(get_prefix, axis=1).sum()
C T
0 62 33
1 145 99
相同的想法,但使用 itertools
替代
from itertools import takewhile
df.groupby(
lambda x: ''.join(takewhile(str.isalpha, x)),
axis=1
).sum()
C T
0 62 33
1 145 99
pandas.Index.str.extract
我们可以使用 callable
,也可以不使用。
df.groupby(df.columns.str.extract('(\D+)', expand=False), axis=1).sum()
C T
0 62 33
1 145 99