欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python dataframe是什么_python – 逐个构建DataFrame的最快方法是什么?

发布时间:2025/4/5 python 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python dataframe是什么_python – 逐个构建DataFrame的最快方法是什么? 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我正在从bloomberg下载价格数据,并希望以最快和最少内存密集的方式构建DataFrame.假设我通过python向bloomberg提交数据请求,以获取从1-1-2000到1-1-2013的所有当前S& P 500股票的价格数据.数据由股票代码返回,然后是日期和价值,一次一个.我目前的方法是为要存储的日期创建一个列表,并为要存储的价格创建另一个列表,并在从Bloomberg数据请求响应中读取每个列表时附加日期和价格.然后,当为特定的股票代码读取所有日期和价格时,我使用了为股票代码创建一个DataFrame

ticker_df = pd.DataFrame(price_list, index = dates_list, columns= [ticker], dtype=float)

我为每个股票代码执行此操作,将每个股票代码数据框附加到列表<< df_list.append(ticker_df)>>读取每个股票代码的数据后.制作完所有的股票代码数据帧后,我将所有单个DataFrame合并为一个DataFrame:

lg_index = []

for num in range(len(df_list)):

if len(lg_index) < len(df_list[num].index):

lg_index = df_list[num].index # Use the largest index for creating the result_df

result_df = pd.DataFrame(index= lg_index)

for num in range(len(df_list)):

result_df[df_list[num].columns[0]] = df_list[num]

我这样做的原因是因为每个股票代码的指数不相同(如果股票去年只有IPO,等等)

我猜我必须有一个更好的方法来完成我在这里使用更少的内存和更快的方式,我只是想不到它.谢谢!

解决方法:

我不是100%肯定你的后续,但你可以连接一个DataFrames列表:

pd.concat(df_list)

例如:

In [11]: df = pd.DataFrame([[1, 2], [3, 4]])

In [12]: pd.concat([df, df, df])

Out[12]:

0 1

0 1 2

1 3 4

0 1 2

1 3 4

0 1 2

1 3 4

In [13]: pd.concat([df, df, df], axis=1)

Out[13]:

0 1 0 1 0 1

0 1 2 1 2 1 2

1 3 4 3 4 3 4

或做一个外部合并/加入:

In [14]: df1 = pd.DataFrame([[1, 2]], columns=[0, 2])

In [15]: df.merge(df1, how='outer') # do several of these

Out[15]:

0 1 2

0 1 2 2

1 3 4 NaN

标签:python,memory,dataframe,pandas,performance

来源: https://codeday.me/bug/20190703/1369366.html

总结

以上是生活随笔为你收集整理的python dataframe是什么_python – 逐个构建DataFrame的最快方法是什么?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。