我正在与一家前大型数据公司合作。这是一个示例:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'ID': ['A', 'A', 'A', 'X', 'X', 'Y'],
})
ID
0 A
1 A
2 A
3 X
4 X
5 Y
Run Code Online (Sandbox Code Playgroud)
现在,给定“ID”列中每个值的频率,我想使用下面的函数计算权重,并添加一个具有与“ID”中每个值关联的权重的列。
def get_weights_inverse_num_of_samples(label_counts, power=1.):
no_of_classes = len(label_counts)
weights_for_samples = 1.0/np.power(np.array(label_counts), power)
weights_for_samples = weights_for_samples/ np.sum(weights_for_samples)*no_of_classes
return weights_for_samples
freq = df.value_counts()
print(freq)
ID
A 3
X 2
Y 1
weights = get_weights_inverse_num_of_samples(freq)
print(weights)
[0.54545455 0.81818182 1.63636364]
Run Code Online (Sandbox Code Playgroud)
因此,我正在寻找一种有效的方法来获取这样的数据帧,给定上述权重:
ID sample_weight
0 A 0.54545455
1 A 0.54545455
2 A 0.54545455 …Run Code Online (Sandbox Code Playgroud) 我从这里借用这个例子。我有一个这样的数据框:
# Import pandas package
import pandas as pd
# Define a dictionary containing ICC rankings
rankings = {'test': ['India', 'South Africa', 'England',
'New Zealand', 'Australia'],
'odi': ['England', 'India', 'New Zealand',
'South Africa', 'Pakistan'],
't20': ['Pakistan', 'India', 'Australia',
'England', 'New Zealand']}
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
# Before renaming the columns
print(rankings_pd)
test odi t20
0 India England Pakistan
1 South Africa India India
2 England New Zealand Australia
3 New Zealand South Africa …Run Code Online (Sandbox Code Playgroud) 我正在初始化这样的序列
seq = {'a', 'b', 'c', 'd', 'e'}
Run Code Online (Sandbox Code Playgroud)
现在我使用 fromkeys() 将序列转换为集合字典。这就是我正在做的事情:
val = set()
seq_dict = dict.fromkeys(seq, val)
Run Code Online (Sandbox Code Playgroud)
现在看来,如果仅将一个元素添加到我的字典键集中之一,则该元素将被添加到所有其他集合中。这是示例:
seq_dict['a'].add("val1")
print(seq_dict)
{'d': {'val1'}, 'c': {'val1'}, 'b': {'val1'}, 'a': {'val1'}, 'e': {'val1'}}
Run Code Online (Sandbox Code Playgroud)
不确定我是否以正确的方式使用 fromkeys ?
在以下示例中,我有两个字典。
d1 = {'A' : 1, 'B' : 2,'C' : 9}
d2 = {'A' : 5, 'B' : 1,'C' : 10}
Run Code Online (Sandbox Code Playgroud)
现在,要找到具有最小值的密钥,我只需使用
min_d1 = min(d1, key=d1.get)
min_d2 = min(d2, key=d2.get)
print(min_d1, min_d2) # A B
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否有一种有效的方法可以找到在上述两个字典中具有最小平均值的键,而不必遍历所有 dics 键?例如,在上面的例子中,我希望得到B作为输出。