gpt4 book ai didi

python - 使用现有列和字典的 Pandas 新列

转载 作者:行者123 更新时间:2023-12-04 03:30:40 26 4
gpt4 key购买 nike

我有一个如下所示的数据框:

df = pd.DataFrame({"user_id" : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
"score" : [0, 100, 50, 0, 25, 50, 100, 0, 7, 20],
"valval" : ["va2.3", "va1.1", "va2.1", "va2.2", "va1.2",
"va1.1", "va2.1", "va1.2", "va1.2", "va1.3"]})

print(df)


| user_id | score | valval
-----+---------+-------+--------
0 | a | 0 | va2.3
1 | b | 100 | va1.1
2 | c | 50 | va2.1
3 | d | 0 | va2.2
4 | e | 25 | va1.2
5 | f | 50 | va1.1
6 | g | 100 | va2.1
7 | h | 0 | va1.2
8 | i | 7 | va1.2
9 | j | 20 | va1.3

我还有一本字典,如下所示:

dic_t = { "key1" : ["va1.1", "va1.2", "va1.3"], "key2" : ["va2.1", "va2.2", "va2.3"]}

我想要一个新列“keykey”。

此列的值具有其对应值的字典键。

结果看起来像这样:

     | user_id | score | valval | keykey 
----------------------------------------
0 | a | 0 | va2.3 | key2
1 | b | 100 | va1.1 | key1
2 | c | 50 | va2.1 | key2
3 | d | 0 | va2.2 | key2
4 | e | 25 | va1.2 | key1
5 | f | 50 | va1.1 | key1
6 | g | 100 | va2.1 | key2
7 | h | 0 | va1.2 | key1
8 | i | 7 | va1.2 | key1
9 | j | 20 | va1.3 | key1

最佳答案

将字典展平后就可以使用series.map了;

d = {val:k for k,v in dic_t.items() for val in v}
df['keykey'] = df['valval'].map(d)

print(df)

user_id score valval keykey
0 a 0 va2.3 key2
1 b 100 va1.1 key1
2 c 50 va2.1 key2
3 d 0 va2.2 key2
4 e 25 va1.2 key1
5 f 50 va1.1 key1
6 g 100 va2.1 key2
7 h 0 va1.2 key1
8 i 7 va1.2 key1
9 j 20 va1.3 key1

关于python - 使用现有列和字典的 Pandas 新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66909332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com