熊猫:for循环使用两个或多个值的组合?

时间:2018-02-22 08:31:15

标签: python pandas

假设我有下表:

table1 = pd.DataFrame([{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
     {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
     {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 },
                       {'account': 'Jones LLC', 'Jan': 1350, 'Feb': 1200, 'Mar': 1404},
                        {'account': 'Alpha Co',  'Jan': 300, 'Feb': 400, 'Mar': 500}])


table2 = pd.DataFrame(['Jones LLC','Alpha Co', 'Blue Inc', 'Another Company'], columns=['account'] )
  1. 我正在尝试在table2中创建一个名为" frequency"计算表2中每个值在table1['account']中出现的次数。我该怎么做?

  2. 除此之外,让我们说我希望我的for循环频率计数仅应用于table1中table1[Jan]的值大于200的行。我该怎么写这个"多个标准" for loop?

  3. 我是否错误地思考了这个问题?我根本不应该选择使用for循环吗?谢谢!

2 个答案:

答案 0 :(得分:2)

mapvalue_counts

一起使用

第1部分

In [876]: table2['freq'] = table2.account.map(table1.account.value_counts())

In [877]: table2
Out[877]:
           account  freq
0        Jones LLC   2.0
1         Alpha Co   2.0
2         Blue Inc   1.0
3  Another Company   NaN

第2部分

In [884]: table2['freqJAN>200'] = table2.account.map(
                           table1.query('Jan > 200').account.value_counts())

In [885]: table2
Out[885]:
           account  freq  freqJAN>200
0        Jones LLC   2.0          1.0
1         Alpha Co   2.0          1.0
2         Blue Inc   1.0          NaN
3  Another Company   NaN          NaN

table1[table1.Jan.gt(200)].account取代table1.query('Jan > 200').account

答案 1 :(得分:0)

table3 = table1.groupby('account').size().to_frame('freq')
print(table3)

输出:

           freq
account        
Alpha Co      2
Blue Inc      1
Jones LLC     2

或者,如果您需要公司列表中的统计数据:

table3 = table1.groupby('account').size().to_frame('freq').reindex(
                                        table2.account,fill_value=0)
print(table3)

输出:

                 freq
account              
Jones LLC           2
Alpha Co            2
Blue Inc            1
Another Company     0
相关问题