簡體   English   中英

將 CSV 導入 pandas,其中一列包含所有列名,另一列包含所有值

[英]Importing CSV into pandas with one column that contains all column names and another containing all the values

我想將 CSV 導入熊貓。 我目前使用 for 循環並將 CSV 轉換為字典,然后再將其轉換為數據框。

數據如下所示:

| row id | attr name | attr value |
| ______ | _________ | __________ |
| 5      | beans.    | 1.         | 
| 5.     | fruit.    | 2          |
| 5.     | claw.     | 2          |
| 5.     | house.    | 1          |
| 5.     | nuts.     | 0          |
| 6.     | beans.    | 0          |
| 6.     | fruit.    | 1          |
| 6.     | claw.     | 2          |
| 6.     | house.    | 3          |
| 6.     | nuts.     | 0          |

我希望它看起來像這樣:

| row id | beans | fruit | claw | house | nuts |
| ______ | _____ | _____ | ____ | _____ | ____ |
| 5.     | 1     | 2     | 2    | 1     | 0    |
| 6.     | 0     | 1     | 2    | 3     | 0    |

這完全有可能自動完成嗎? 還是我應該堅持我的 for 循環逐行讀取它?

嘗試:

df.pivot(index='row id', columns=['attr name'], values=['attr value'])

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html

你要做的是重塑框架 您可以通過支點來實現這一點

df.pivot(index="id",  columns="name", values="value")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM