【问题标题】:Looping through grouped and assign value in new column in python在python的新列中循环分组并赋值
【发布时间】:2021-06-24 21:47:48
【问题描述】:

我想创建一个新列并为每个组(在本例中为颜色)和每个组分配值:

如果 Function 列是 View 而 Access 列是 no,则该组的新列的值为“No”;

如果 Function column = View and Access column = yes,则新列的值将与组中行的“Access”相同

数据:

Type Color Function Access
A Blue Add yes
A Blue View no
A Red Add no
A Red View yes
B Blue Add yes
B Blue View no

期望的结果:

Type Color Function Access New Column
A Blue Add yes no
A Blue View no no
A Red Add no no
A Red View yes yes
B Blue Add yes no
B Blue View no no
# I created a new column first before grouping them
data['New Column'] = ''
data_grouped = data.groupby(['Type', 'Color']

# attempted to loop but stuck here #
for group_name, df_group in data_grouped:
    print(format(group_name))

    for row_index, row in df_group.iterrows():

        if (row['Function'] == 'View') & (row['Access'] == 'no'):
            row['New Column'] = 'no'

        print(col, column_type)

【问题讨论】:

  • df['Function'] == 'Add 时会发生什么?
  • 你好,如果是df['Function'] == 'Add',没关系。只要是 df['Function'] == 'View' 和 df['Access'] == 'No',该分组的行应该是 df['New Column'] == 'No'。如果 df['Function'] == 'View' 和 df['Access'] == 'Yes',那么对于该分组中的每一行,新列应该是来自 df['Access'] 的值。希望这更清楚。谢谢。

标签: python pandas dataframe pandas-groupby


【解决方案1】:

考虑到您希望对所有其他情况都使用“否”(View-Yes 对除外),您可以执行以下操作:

data['New Column'] = np.where((data['Function']=='View') & (data['Access']=='yes'), 'yes', 'no')

【讨论】:

  • 嗨,谢谢,但是如果 data['Function']=='View') & (data['Access']=='yes', data['New Column'] 应该遵循来自 data['Access'] 的值。如果 data['Function']=='Add' 和 access = no 对于同一组数据['Function']=='View',则它可以是值'No')& (数据['访问']=='是'
猜你喜欢
  • 2017-07-08
  • 2020-10-25
  • 2014-01-08
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2015-03-01
  • 2017-08-04
相关资源
最近更新 更多