【发布时间】:2019-04-17 18:07:06
【问题描述】:
我正在尝试向数据框中添加一个新列,其中仅包含现有列中的唯一值。新列中的行数可能会减少,其中 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,) ()
【问题讨论】:
标签: python python-3.x pandas numpy unique