数据帧排序

2024-03-28 13:10:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究Python pandas,首先对从csv文件创建的数据帧进行排序。我最终尝试创建一个for循环,使用值进行比较。但是,当我打印新值时,它们使用的是原始数据帧,而不是排序后的版本。我如何正确地做下面的工作?你知道吗

原始CSV数据:

date          fruit     quantity
4/5/2014 13:34  Apples      73
4/5/2014 3:41   Cherries    85
4/6/2014 12:46  Pears       14
4/8/2014 8:59   Oranges     52
4/10/2014 2:07  Apples      152
4/10/2014 18:10 Bananas      23
4/10/2014 2:40  Strawberries  98

代码:

import pandas as pd
import numpy

df = pd.read_csv('example2.csv', header=0, dtype='unicode')
df_count = df['fruit'].value_counts()
x = 0 #starting my counter values or position in the column
df.sort_values(['fruit'], ascending=True, inplace=True) #sorting the column 
fruit
print(df)
old_fruit = df.fruit[x]
new_fruit = df.fruit[x+1]
print(old_fruit) 
print(new_fruit)

Tags: csvthe数据importtruepandasdf排序