基于熊猫中的索引列表添加新列



我有一个类似pandas的数据帧,

pd.DataFrame({'f1':[23,56,7, 56,34, 98],
'f2':[32,85,27, 36,64, 60]})
f1  f2
0   23  32
1   56  85
2   7   27
3   56  36
4   34  64
5   98  60

基于像index_list = [2, 4]这样的索引列表,我想在原始数据图中添加一个新列,如下

new_column  f1  f2
0      0        23  32
1      0        56  85
2      0        7   27
3      1        56  36
4      1        34  64
5      2        98  60

注意:索引列表显示new_column应增加1个整数的位置。

# Put a 1 after the index of each index in your list as a new column.
df.loc[[x+1 for x in index_list], 'new_column'] = 1
# fill with 0's, and take the cumulative sum.
df.new_column = df.new_column.fillna(0).cumsum()
print(df)

输出:

f1  f2  new_column
0  23  32         0.0
1  56  85         0.0
2   7  27         0.0
3  56  36         1.0
4  34  64         1.0
5  98  60         2.0

如果您的索引列表实际上是一个索引:

# If index_list looks like:
>>> index_list
Int64Index([2, 4], dtype='int64')
# Then you can do:
df.loc[index_list+1, 'new_column'] = 1
...

一个简单的方法是使用cumsum:

df = pd.DataFrame(index=range(6))
index_list = [2, 4]
index_list = [x+1 for x in index_list]
df["new"] = 0
df["new"].loc[index_list] = 1
df["new"].cumsum()

它给出:

0    0
1    0
2    0
3    1
4    1
5    2

这里有一种方法可以在不需要cumsum():的情况下获得问题中指定的确切输出

df = ( df.assign(new_column=pd.Series(
range(1, 1+len(index_list)), 
index=pd.Series(index_list)+1))
.ffill().fillna(0).astype(int)[['new_column'] + list(df.columns)] )

输出:

new_column  f1  f2
0           0  23  32
1           0  56  85
2           0   7  27
3           1  56  36
4           1  34  64
5           2  98  60

最新更新