我正在尝试向数据框中添加一个新列,其中只有来自现有列的唯一值。新列中的行可能会减少,其中 np.nan 值可能会出现重复项。
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,3,4,5], 'b':[3,4,3,4,5]})
df
a b
0 1 3
1 2 4
2 3 3
3 4 4
4 5 5
目标:
a b c
0 1 3 3
1 2 4 4
2 3 3 nan
3 4 4 nan
4 5 5 5
我试过了:
df['c'] = np.where(df['b'].unique(), df['b'], np.nan)
它抛出: operands could not be broadcast together with shapes (3,) (5,) ()
牛魔王的故事
犯罪嫌疑人X
相关分类