Python 熊猫:对于使用两个或多个值的组合的循环?
假设我有下表:Python 熊猫:对于使用两个或多个值的组合的循环?,python,pandas,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 },
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'] )
table1['account']
中出现的次数。我该怎么做table1[Jan]
的值大于200的行。我应该如何为循环编写“多个条件”我是不是对这个问题想错了?我应该根本不选择使用for循环吗?谢谢大家! 将
map
与value\u计数一起使用
第一部分
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
第二部分
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)]。账户
代替table1.query('Jan>200')。账户
使用地图
和数值
table3 = table1.groupby('account').size().to_frame('freq')
print(table3)
第一部分
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
第二部分
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)]。科目
代替table1.query('Jan>200')。科目
table3 = table1.groupby('account').size().to_frame('freq')
print(table3)
输出:
freq
account
Alpha Co 2
Blue Inc 1
Jones LLC 2
freq
account
Jones LLC 2
Alpha Co 2
Blue Inc 1
Another Company 0
或者,如果您需要公司列表上的统计信息:
table3 = table1.groupby('account').size().to_frame('freq').reindex(
table2.account,fill_value=0)
print(table3)
输出:
freq
account
Alpha Co 2
Blue Inc 1
Jones LLC 2
freq
account
Jones LLC 2
Alpha Co 2
Blue Inc 1
Another Company 0
输出:
freq
account
Alpha Co 2
Blue Inc 1
Jones LLC 2
freq
account
Jones LLC 2
Alpha Co 2
Blue Inc 1
Another Company 0
或者,如果您需要公司列表上的统计信息:
table3 = table1.groupby('account').size().to_frame('freq').reindex(
table2.account,fill_value=0)
print(table3)
输出:
freq
account
Alpha Co 2
Blue Inc 1
Jones LLC 2
freq
account
Jones LLC 2
Alpha Co 2
Blue Inc 1
Another Company 0
谢谢你,零!然而,第2部分是不是完全不能从for循环中实现呢?你可以循环,但在与pandas合作以提高速度时最好避免for循环。谢谢你!然而,第2部分完全不能从for循环中实现吗?您可以循环,但在与pandas一起工作以提高速度时,最好避免for循环。