python - pandas:每行计算相同的值

时间:2016-12-26 02:37:33

标签: python pandas

我有一个数据框,如:

                          investing.com                                  ft                      bloomberg
19        API Weekly Distillates Stocks                                 NaN                                 NaN
20            API Weekly Gasoline Stock                                 NaN                                 NaN
21                                  NaN         Advance Goods Trade Balance         Advance Goods Trade Balance
22                                  NaN                                 NaN                Advance Retail Sales
23                        All Car Sales                                 NaN                                 NaN
24                      All Truck Sales                                 NaN                                 NaN
25          Average Hourly Earnings MoM         Average Hourly Earnings MoM         Average Hourly Earnings MoM
26                                  NaN                                 NaN         Average Hourly Earnings YoY

我想添加一个列,其中包含所有不是NaN的值的计数。

我试过了:

df['count of not NaN'] = df.apply(lambda x:(x[['investing.com','ft','bloomberg']] != 'NaN').count(), axis=1)

但它不起作用。谁知道为什么/可以帮助我正确的配方? (我知道这个问题的某些风格已经发布,但它们无法真正帮助我取得成功......) 谢谢!

1 个答案:

答案 0 :(得分:3)

count方法就是这样做的。使用轴= 1来添加列。

df.count(axis=1)