使用chunksize选择数据但保持相同的顺序?

时间:2016-07-05 19:42:49

标签: python python-2.7 pandas

以下是我使用chunksize从数据库中选择数据的程序。

# Give my large required list
subset = pd.read_csv(required_list, index_col=[0], low_memory=False).index.unique()

# give my large database, it would select data based on column name
tp = pd.read_csv(Database,iterator=True, chunksize=1000, usecols=subset, low_memory=False) 
df = pd.concat(tp, ignore_index=True)

df.to_csv(OutputFile,iterator=True, chunksize=1000)

但是当我运行程序时,输出文件中的数据顺序将会改变。

例如。

# Required_list, giving the column name that I want to select.
2
3
1

# Database
1 2 3 4 5  
a b c d e 

# OutputFile. The order is 1, 2, 3, not 2, 3, 1.
1 2 3 
a b c 

# But I want the output file to follow the same order as requried_list
2 3 1 
b c a

所以我的问题是,我如何修改程序来选择数据,但仍然保持与required_list相同的顺序?由于数据非常大,因此需要函数iteratorchunksize

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

df = pd.concat(tp, ignore_index=True)[subset]

pd.concat(tp, ignore_index=True)返回一个数据框,df[list_of_cools] - 返回一个DataFrame,其列的排序方式与list_of_cools列表中的一样