python中的表函数
我有两个变量python中的表函数,python,Python,我有两个变量 a b Less than 5 Yes Less than 5 No Less than 5 Yes Less than 5 No Less than 5 Yes Greater than 5 No Greater than 5 Yes Greater than 5 No Greater than 5 Yes 我想要一张桌子,上面有
a b
Less than 5 Yes
Less than 5 No
Less than 5 Yes
Less than 5 No
Less than 5 Yes
Greater than 5 No
Greater than 5 Yes
Greater than 5 No
Greater than 5 Yes
我想要一张桌子,上面有
Yes No
Less than 5 3 2
Greater than 5 2 2
我基本上想要python中R的表函数
有人能帮我做这件事吗
谢谢假设列表a和b的长度始终相同
distinct = set(a)
for type in distinct:
yes = [b[i] for i in range(len(b)) if a[i] == type].count('yes')
no = [b[i] for i in range(len(b)) if a[i] == type].count('no')
print type, yes, no
花式格式不包括在内
import petl
a = ['Less than 5', 'Less than 5','Less than 5','Less than 5','Less than 5',
'Greater than 5','Greater than 5','Greater than 5','Greater than 5',]
b = ['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes']
cols = [a, b]
table = petl.fromcolumns(cols)
yes_table = petl.addfield(table, 'Yes_addition', lambda rec: 1 if rec['f1'] == 'Yes' else 0)
yes_table = petl.aggregate(yes_table, 'f0', sum, 'Yes_addition')
yes_table = petl.rename(yes_table, 'value', 'Yes')
no_table = petl.addfield(table, 'No_addition', lambda rec: 0 if rec['f1'] == 'Yes' else 1)
no_table = petl.aggregate(no_table, 'f0', sum, 'No_addition')
no_table = petl.rename(no_table, 'value', 'No')
joined = petl.join(yes_table, no_table, key='f0')
print petl.lookall(joined)
as_dictionary = petl.dicts(joined)
上述输出将产生以下结果(以及as_dictionary变量将是一个可以在代码中其他地方轻松使用的字典):
别忘了安装petl
pip install petl
最好的做法是提供一个最小的可复制示例。
pip install petl