python - 有没有办法将 numpy 数组映射到某个数据框?

标签 python python-3.x pandas numpy

我有一个 DataFrame,比方说:

#d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} // that's what the data might look like
df = pd.DataFrame(data=d)

我有一个带有 [0, 2] 的 np 数组。

现在我想向 DataFrame 添加一列,当行的索引在 np 数组中时为 1,否则为 0。

有人有想法吗?

最佳答案

使用Index.isin将掩码转换为整数:

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} 
df = pd.DataFrame(data=d)

a = np.array([0, 2])

df['new'] = df.index.isin(a).astype(int)
#alternative
#df['new'] = np.in1d(df.index, a).astype(int)

或者使用numpy.where :

df['new'] = np.where(df.index.isin(a), 1, 0)
#alternative
#df['new'] = np.where(np.in1d(df.index, a), 1, 0)

print (df)
   col1  col2  new
0     1     3    1
1     2     4    0
2     3     5    1

关于python - 有没有办法将 numpy 数组映射到某个数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58692801/

相关文章:

跨开源模块的 Python 日志记录

python-3.x - tkinter 的 askopenfilename 的替代方案

pandas - 使 groupby.apply 更高效或转换为 spark

pandas - 在饼图 pandas 上显示一个标签

python-3.x - OpenCV Python Numpy : ValueError: too many values to unpack (expected 2)

pandas - 从 Pandas 数据框中绘制堆积条形图和多个条形图

python - 如何使用 Imdbpy 库获取电影的长度?

python - 在数据框中查找列表中的最后一个值

python - 编程错误: Incorrect number of bindings supplied

python - 使用特定掩码正则表达式 python 格式化数字