如何使用布尔过滤器获取此模式?

2024-05-17 08:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在探索一个数据集,只想在受试者回答X(在本例中为“可爱”)时才使用“性”列的模式

到目前为止,我已经用以下逻辑做了一些事情。从“性”中得到了假人,有一个“男性”(0,1)栏。从那里,我试着做

i_1_1 = clean_USA['Male'][clean_USA['Image1_1']=='cute']
i_mode = i_1_1.mode()

我试过几次,但还是失败了。这次我得到了“keyrerror:'Male'”作为输出。也许R中的这个看起来像:

i_1 <- mode(clean_USA$Male(clean_USA$Image1_1=='cute'))

也许,也许不是。我刚刚开始编写代码,所以我非常感谢您的建议。你将如何解决这个问题

这是我的df负责人:

{'Nationality': {0: 'United States',
  1: 'United States',
  2: 'United States',
  3: 'United States',
  4: 'United States'},
 'Sex': {0: 'Female', 1: 'Female', 2: 'Female', 3: 'Female', 4: 'Female'},
 'Age': {0: 62, 1: 43, 2: 47, 3: 26, 4: 34},
 'Image1_1': {0: 'noun', 1: 'cute', 2: 'cute', 3: 'noun', 4: 'pretty'},
 'Image1_2': {0: 'cute', 1: 'happy', 2: 'lovely', 3: 'noun', 4: 'stunning'},
 'Image1_3': {0: 'happy', 1: 'clean', 2: 'crazy', 3: 'verb', 4: 'cute'},
 'Image2_1': {0: 'noun', 1: 'beautiful', 2: 'nice', 3: 'happy', 4: 'cute'},
 'Image2_2': {0: 'calm', 1: 'nice', 2: 'funny', 3: 'noun', 4: 'calm'},
 'Image2_3': {0: 'funny', 1: 'happy', 2: 'excited', 3: 'good', 4: 'lovely'},
 'Image3_1': {0: 'noun', 1: 'beautiful', 2: 'verb', 3: 'noun', 4: 'gorgeous'},
 'Image3_2': {0: 'happy', 1: 'happy', 2: 'faithful', 3: 'young', 4: 'elegant'},
 'Image3_3': {0: 'excited', 1: 'verb', 2: 'funny', 3: 'teen', 4: 'knockout'},
 'Image4_1': {0: 'noun', 1: 'worried', 2: 'super', 3: 'sad', 4: 'lovely'},
 'Image4_2': {0: 'noun', 1: 'lazy', 2: 'nice', 3: 'noun', 4: 'cute'},
 'Image4_3': {0: 'funny', 1: 'cute', 2: 'kind', 3: 'noun', 4: 'lovely'},
 'Image5_1': {0: 'noun', 1: 'cute', 2: 'crazy', 3: 'noun', 4: 'taking'},
 'Image5_2': {0: 'cute', 1: 'happy', 2: 'cute', 3: 'noun', 4: 'bonny'},
 'Image5_3': {0: 'calm', 1: 'nice', 2: 'lovely', 3: 'noun', 4: 'exquisite'},
 'Image6_1': {0: 'noun', 1: 'wonderful', 2: 'colorful', 3: 'happy', 4: 'good'},
 'Image6_2': {0: 'verb', 1: 'nice', 2: 'great', 3: 'positive', 4: 'fine'},
 'Image6_3': {0: 'calm',
  1: 'happy',
  2: 'temporary',
  3: 'optimistic',
  4: 'nice'},
 'Image7_1': {0: 'old', 1: 'clean', 2: 'lucky', 3: 'noun', 4: 'noun'},
 'Image7_2': {0: 'noun', 1: 'chubby', 2: 'obedient', 3: 'verb', 4: 'likely'},
 'Image7_3': {0: 'calm', 1: 'happy', 2: 'verb', 3: 'old', 4: 'nonword'},
 'Image8_2': {0: 'verb', 1: 'sweet', 2: 'tasty', 3: 'bake', 4: 'smooth'},
 'Image8_3': {0: 'taste', 1: 'nice', 2: 'delicious', 3: 'noun', 4: 'soft'},
 'Male': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}}

谢谢


Tags: cleancutemalefemalefunnyunitednicenoun
2条回答

这就是你想要的

df.loc[df.Image1_1 == "cute", ["Sex"]].mode()

      Sex
0  Female

当您需要列的mode时,不确定索引Male的意义是什么。如果排除除一个值以外的所有值,则模式就是该值

无论您想做什么,都不能在创建“男性”列之前访问该列。但我猜没有必要创建新的列

如果我理解正确,您希望:

i_1_1 = clean_USA[clean_USA['Image1_1']=='cute']
i_mode = i_1_1['Sex'].mode()

编辑: 所以你创建了这个专栏,但我没有看到。那么它应该是这样的

i_1_1 = clean_USA[clean_USA['Image1_1']=='cute']
i_mode = i_1_1['Male'].mode()

相关问题 更多 >