我试图计算数据帧各列中每行的唯一值数。
More context in my previous post and my answer
以下是当前的数据框:
[in] df
[out]
PID CID PPID PPPID PPPPID PPPPPID
0 2015-01-02 456 2014-01-02 2014-01-02 2014-01-02 2014-01-02
1 2015-02-02 500 2014-02-02 2013-02-02 2012-02-02 2012-02-10
2 2010-12-04 300 2010-12-04 2010-12-04 2010-12-04 2010-12-04
除CID(contract_ID)之外的所有列都是日期时间。我想在数据框中添加另一列,计算每行中唯一日期时间的数量(为了找出"链中有多少合同")。
我已经尝试了.count()
和.sum()
方法的不同实现,但无法让它们逐行工作(输出是所有行的相同的价值)。
示例:
df_merged['COUNT'] = df_merged2.count(axis=1)
填写整个' COUNT'列' 6'我希望每一行都有所不同。
删除axis=1
参数会使整个列“NaN'
答案 0 :(得分:2)
您需要apply(your_func, axis=1)
逐行处理。
df
Out[19]:
PID CID PPID PPPID PPPPID PPPPPID
0 2015-01-02 456 2014-01-02 2014-01-02 2014-01-02 2014-01-02
1 2015-02-02 500 2014-02-02 2013-02-02 2012-02-02 2012-02-10
2 2010-12-04 300 2010-12-04 2010-12-04 2010-12-04 2010-12-04
df['counts'] = df.drop('CID', axis=1).apply(lambda row: len(pd.unique(row)), axis=1)
Out[20]:
PID CID PPID PPPID PPPPID PPPPPID counts
0 2015-01-02 456 2014-01-02 2014-01-02 2014-01-02 2014-01-02 2
1 2015-02-02 500 2014-02-02 2013-02-02 2012-02-02 2012-02-10 5
2 2010-12-04 300 2010-12-04 2010-12-04 2010-12-04 2010-12-04 1
[3 rows x 7 columns]
答案 1 :(得分:1)
另一种方法是在你的df的转置上调用unique
:
In [26]:
df['counts'] = df.drop('CID', axis=1).T.apply(lambda x: len(pd.Series.unique(x)))
df
Out[26]:
PID CID PPID PPPID PPPPID PPPPPID counts
0 2015-01-02 456 2014-01-02 2014-01-02 2014-01-02 2014-01-02 2
1 2015-02-02 500 2014-02-02 2013-02-02 2012-02-02 2012-02-10 5
2 2010-12-04 300 2010-12-04 2010-12-04 2010-12-04 2010-12-04 1
答案 2 :(得分:1)
您可以在nunique
上直接使用DataFrame
。这是从pd.__version__ == u'0.20.0'
开始。
In [169]: df['counts'] = df.drop('CID', axis=1).nunique(axis=1)
In [170]: df
Out[170]:
PID CID PPID PPPID PPPPID PPPPPID counts
0 2015-01-02 456 2014-01-02 2014-01-02 2014-01-02 2014-01-02 2
1 2015-02-02 500 2014-02-02 2013-02-02 2012-02-02 2012-02-10 5
2 2010-12-04 300 2010-12-04 2010-12-04 2010-12-04 2010-12-04 1