我想就如何正确地做这件事征求一些建议。我对蟒蛇很陌生。
最初,我想找出多个索引组合的计数器/频率。我尝试了几种方法,例如循环、迭代、迭代等等,我意识到使用collections.Counter是最快、开销最少的。
但是,它返回多索引索引组合的元组列表作为计数器剪裁键。元组的键使得以后的处理很困难。
因此,我正在研究如何用分隔符将它们变成字符串,以便以后的处理更容易管理。
例如,下面这个多索引:
# testing
def testing():
testing_df = pd.read_csv("data/testing.csv", float_precision="high")
testing_df = testing_df.set_index(["class", "table", "seat"]).sort_index()
print("\n1: \n" + str(testing_df.to_string()))
print("\n2 test: \n" + str(testing_df.index))
occurrences = collections.Counter(testing_df.index)
print("\n3: \n" + str(occurrences))产出:
1:
random_no
class table seat
Emerald 1 0 55.00
Ruby 0 0 33.67
0 24.01
1 87.00
Topaz 0 0 67.00
2 test:
MultiIndex([('Emerald', 1, 0),
( 'Ruby', 0, 0),
( 'Ruby', 0, 0),
( 'Ruby', 0, 1),
( 'Topaz', 0, 0)],
names=['class', 'table', 'seat'])
3:
Counter({('Ruby', 0, 0): 2, ('Emerald', 1, 0): 1, ('Ruby', 0, 1): 1, ('Topaz', 0, 0): 1})正如我们从3中可以看到的那样,它将不同数据类型的元组组合作为切分键返回,并使其难以处理。
我试图分离它或使它字符串,这样处理它就更容易了。
在下面尝试时有错误:
x = "|".join(testing_df.index)
print(x)
x = "|".join(testing_df.index)
TypeError: sequence item 0: expected str instance, tuple found和下面有错误
x = "|".join(testing_df.index[0])
print(x)
x = "|".join(testing_df.index[0])
TypeError: sequence item 1: expected str instance, numpy.int64 found基本上,要么是:
。
我能问一问我该如何正确地做这件事吗?
非常感谢!
发布于 2021-09-09 10:18:52
我可以为2提供一个解决方案,将键元组转换为字符串:
from collections import Counter
# recreate your problem
occurrences = Counter([('Ruby', 0, 0),
('Ruby', 0, 0),
('Emerald', 1, 0),
('Ruby', 0, 1),
('Topaz', 0, 0)])
# convert tuple keys to string keys
new_occurrences = {'|'.join(str(index) for index in key) : value for key,value in occurrences.items()}
print(new_occurrences){'Ruby|0|0': 2, 'Emerald|1|0': 1, 'Ruby|0|1': 1, 'Topaz|0|0': 1}Counter是dict的一个子类,因此您可以使用dict理解和.items()等花哨的东西同时遍历键和值。
根据您打算如何进一步处理数据,将计数器的结果转换为pandas DataFrame可能更有用。仅仅因为pandas提供了更多更简单的处理功能。
下面是操作步骤:
import pandas as pd
df = pd.DataFrame({'class': [k[0] for k in occurrences.keys()],
'table': [k[1] for k in occurrences.keys()],
'seat': [k[2] for k in occurrences.keys()],
'counts': [v for _,v in occurrences.items()]})
df.head() class table seat counts
0 Ruby 0 0 2
1 Emerald 1 0 1
2 Ruby 0 1 1
3 Topaz 0 0 1https://stackoverflow.com/questions/67094660
复制相似问题