简体   繁体   English

有没有办法创建 Pandas dataframe 值 map 到索引/行对?

[英]Is there a way to create a Pandas dataframe where the values map to an index/row pair?

I was struggling with how to word the question, so I will provide an example of what I am trying to do below.我一直在为如何表达这个问题而苦苦挣扎,所以我将在下面提供一个我正在尝试做的例子。 I have a dataframe that looks like this:我有一个看起来像这样的 dataframe:

     ID     CODE    COST
0   60086   V2401   105.38
1   60142   V2500   221.58
2   60086   V2500   105.38
3   60134   V2750   35
4   60134   V2020   0

I am trying to create a dataframe that has the ID as rows, the CODE as columns, and the COST as values since the cost for the same code is different per ID.我正在尝试创建一个 dataframe,其 ID 为行,CODE 为列,COST 为值,因为相同代码的成本每个 ID 不同。 How can I do this in?我怎样才能做到这一点?

This seems like a classic "long to wide" problem, and there are several ways to do it.这似乎是一个经典的“从长到宽”的问题,有几种方法可以做到。 You can try pivot , for example:您可以尝试pivot ,例如:

df.pivot_table(index='ID', columns='CODE', values='COST')

(assuming that the dataframe is df .) (假设 dataframe 是df 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM