基于筛选条件和多列索引创建新列?

3

我一直在尝试搜索/思考一个答案,可能需要使用melt或stack等技术,但似乎仍然做不到。

这是我的数据框:

d = {'type' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
 'company' : ['A', 'B', 'C', 'D', 'E','A', 'B', 'C', 'D', 'E'],
 'value type': ['value car','value car','value car','value car','value car', 'value train','value train','value train','value train','value train',],
 'value': [0.1, 0.2, 0.3, 0.4, 0.5, 0.15, 0.25, 0.35, 0.45, 0.55] }

df = pd.DataFrame(d)

这是我想要的内容(左侧是数组,右侧是我想要的结果): enter image description here 如您所见,我希望基于组合(类型,公司)添加一个新列“训练值”。
类似于:
for each row : 
    if (df['value type'] == 'value train'):
        #and (type,company) is the same
        df['train value'] = df['value']
        remove row

例如,类型为1的公司A将在训练价值的新列中拥有一个新值。有没有一种正确的方法来做到这一点?
编辑:::有一个好答案,但我没有清楚地解释自己。我只想要一个仅包含“一个值类型”的新列。例如,我的新DF:
d = {'type' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
 'company' : ['A', 'B', 'C', 'D', 'E','A', 'B', 'C', 'D', 'E'],
 'month' : ['jan', 'feb', 'marc', 'apr', 'may', 'jan', 'feb', 'marc', 'apr', 'sep'],
 'business' : ['business1', 'business2', 'business3', 'business4', 'business5', 'business6', 'business7', 'business8', 'business9', 'business10'], 
 'value time': ['past', 'past', 'past', 'past', 'present', 'present', 'present', 'present', 'future', 'future'],
 'value': [0.1, 0.2, 0.3, 0.4, 0.11, 0.21, 0.31, 0.41, 0.45, 0.55] }

df = pd.DataFrame(d)

这次我需要翻译的内容如下:

这是我这次想要的:enter image description here

如果可能的话,只有“present”值将出现在新列中。类似于

if df['value time'] == 'present' then add to new column

2
你能够粘贴你的数据框而不是截图吗? - ignoring_gravity
1个回答

2

你应该对数据框进行透视:

company_to_type = df.set_index('company')['type'].to_dict()
df = df.pivot(index='company', columns='value type', values='value').reset_index()
df['type'] = df.company.map(company_to_type)
df = df.rename_axis(None, axis=1)
df = df[['type', 'company', 'value train', 'value car']]

您将获得

   type company  value train  value car
0     1       A         0.15        0.1
1     2       B         0.25        0.2
2     3       C         0.35        0.3
3     4       D         0.45        0.4
4     5       E         0.55        0.5

你好,非常感谢您的评论。它帮助我理解了枢轴点的重点。我有一个问题,我的“索引”中有更多的列(我不知道这是否有意义,例如我们有(类型,公司,月份,日期),我想添加其中“值时间”等于某个值的值。我已经更新了我的帖子,更好地解释了问题,请再次帮帮我,好吗? - Mich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接