Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何重新排列CSV?_Python_Excel - Fatal编程技术网

Python 如何重新排列CSV?

Python 如何重新排列CSV?,python,excel,Python,Excel,如何重新排列CSV 我正在尝试将此数据集重新排列为几年,以便: country1 | price | year1 country2 | price | year1 country1 | price | year2 country2 | price | year2 变成: | year1 | year2 country1 | price | price country2 | price | price 我该怎么做呢?试试df.pivot(): 试试看(我使用了链接中的数据

如何重新排列CSV

我正在尝试将此数据集重新排列为几年,以便:

country1 | price | year1
country2 | price | year1
country1 | price | year2
country2 | price | year2
变成:

         | year1 | year2 
country1 | price | price
country2 | price | price

我该怎么做呢?

试试
df.pivot()

试试看(我使用了链接中的数据,并假设您需要哪些列):


您可以使用pandas pivot_表执行此操作:

import pandas as pd
pd.pivot_table(index='Country', columns='Year', values='Price')
输出:

  year    year1  year2
country
country1  price  price
country2  price  price

PythonPandas包允许您操作数据:读取csv、操作它并将其保存为csv。您可能需要根据需要阅读有关
groupby
命令的内容
import pandas as pd
pd.pivot_table(index='Country', columns='Year', values='Price')
  year    year1  year2
country
country1  price  price
country2  price  price