python - 数据框列名 np 数组在列名之一之后有 \n
问题描述
我正在尝试对列列表中选择列的值求和并将其存储在新列中。但是,我不断得到
raise KeyError('%s not in index' % objarr[mask])
KeyError:“['a' 'b' 'c' 'd' 'e'\n 'f'] 不在索引中”
这是我试图实现这一目标的一段代码:
cols = df.columns.values
colIndex = np.argwhere('Person')
selectCols = np.delete(cols, colIndex)
df['total counts'] = df[selectCols].sum(axis=1)
首先,我不确定\n
在列之后是如何出现的e
,其次我不知道是什么导致了这个 KeyError。请帮忙!
解决方案
In [290]: np.argwhere('Person')
Out[290]: array([], shape=(1, 0), dtype=int64)
在中使用它没有意义np.delete
。
节目cols
===
In [301]: cols = np.array(['Person', 'a', 'b', 'c', 'd', 'e', 'f'])
In [302]: idx = np.argwhere('Person')
In [303]: idx
Out[303]: array([], shape=(1, 0), dtype=int64)
In [304]: np.delete(cols, idx)
Out[304]: array(['Person', 'a', 'b', 'c', 'd', 'e', 'f'], dtype='<U6')
或者,我们可以找到cols
等于“人”的位置:
In [305]: idx = np.argwhere(cols=='Person')
In [306]: idx
Out[306]: array([[0]])
In [307]: np.delete(cols, idx)
Out[307]: array(['a', 'b', 'c', 'd', 'e', 'f'], dtype='<U6')
或使用以下列表版本cols
:
In [313]: alist = cols.tolist()
In [314]: alist
Out[314]: ['Person', 'a', 'b', 'c', 'd', 'e', 'f']
In [315]: alist.remove('Person')
In [316]: alist
Out[316]: ['a', 'b', 'c', 'd', 'e', 'f']
===
复制更多您的案例:
In [317]: df = pd.DataFrame(np.ones((2,4),int), columns=['a','b','c','d'])
In [318]: df
Out[318]:
a b c d
0 1 1 1 1
1 1 1 1 1
In [319]: cols = df.columns.values
In [320]: cols
Out[320]: array(['a', 'b', 'c', 'd'], dtype=object)
In [322]: np.argwhere(cols=='a')
Out[322]: array([[0]])
In [323]: np.delete(cols, _)
Out[323]: array(['b', 'c', 'd'], dtype=object)
In [324]: df[_]
Out[324]:
b c d
0 1 1 1
1 1 1 1
In [326]: df[_323].sum(axis=1)
Out[326]:
0 3
1 3
dtype: int64
推荐阅读
- java - Spring Boot with hibernate:创建复合键和多对多关系
- python-3.x - 计算值超过 Dataframe 中特定列的平均值的次数
- c# - 你如何等到所有请求都运行完成
- android - Expo React Native App在android上崩溃
- python - 在熊猫中使用给定的分隔符获取列daframe中所有项目的子字符串
- android - 从对话框返回后,导航 safeArgs 无法导航
- amazon-web-services - Amazon Chime 中的虚拟背景
- python-3.x - 本地 spark 连接到远程 hive 和 hadoop
- mysql - 是否可以在 mysql 中将 2 行合并为 1 行?
- xamarin.forms - Xamarin.Froms MVVMCross 加载模式视图