假设要遍历的列为ColumnA,现在要创建一个名为ColumnB的新列,其中每个单元格都根据ColumnA中的值进行计算和逻辑判断。下面是一些可能的示例:
df['ColumnB'] = np.where(df['ColumnA'] < 5, 0, 1)
df['ColumnB'] = np.where(df['ColumnA'] == 1, 'One',
np.where(df['ColumnA'] == 2, 'Two',
np.where(df['ColumnA'] == 3, 'Three',
np.where(df['ColumnA'] == 4, 'Four', 'Other'))))
df['ColumnB'] = np.select([df['ColumnA'] == 1,
df['ColumnA'] == 2,
df['ColumnA'] == 3,
df['ColumnA'] == 4],
[10, 20, 30, 40],
default=0)
注意:这里示例所使用的np.where和np.select函数需要导入NumPy库,如果还没有安装NumPy,请使用以下代码安装:
!pip install numpy