【发布时间】:2016-03-02 12:09:33
【问题描述】:
我有一个包含大约 100 列的数据框,如下所示:
Id Economics-1 English-107 English-2 History-3 Economics-zz Economics-2 \
0 56 1 1 0 1 0 0
1 11 0 0 0 0 1 0
2 6 0 0 1 0 0 1
3 43 0 0 0 1 0 1
4 14 0 1 0 0 1 0
Histo Economics-51 Literature-re Literatureu4
0 1 0 1 0
1 0 0 0 1
2 0 0 0 0
3 0 1 1 0
4 1 0 0 0
我的目标是只保留全局类别(英语、历史、文学),并在此数据框中分别写出它们组件的值的总和。例如,“English”将是“English-107”和“English-2”之和:
Id Economics English History Literature
0 56 1 1 2 1
1 11 1 0 0 1
2 6 0 1 1 0
3 43 2 0 1 1
4 14 0 1 1 0
为此,我尝试了两种方法。第一种方法:
df = pd.read_csv(file_path, sep='\t')
df['History'] = df.loc[df[df.columns[pd.Series(df.columns).str.startswith('History')]].sum(axes=1)]
第二种方法:
df = pd.read_csv(file_path, sep='\t')
filter_col = [col for col in list(df) if col.startswith('History')]
df['History'] = 0 # initialize value, otherwise throws KeyError
for c in df[filter_col]:
df['History'] = df[filter_col].sum(axes=1)
print df['History', df[filter_col]]
但是,两者都给出了错误:
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
我的问题是:如何调试此错误,或者是否有其他解决方案可以解决我的问题。请注意,我有一个相当大的数据框,大约有 100 列和 400000 行,所以我正在寻找一个优化的解决方案,比如在 pandas 中使用loc。
【问题讨论】:
标签: python pandas dataframe startswith