【问题标题】:Create a large dataframe using Pandas使用 Pandas 创建大型数据框
【发布时间】:2020-06-05 13:50:33
【问题描述】:
df = pd.DataFrame([{'Instrument':'AAA', 'Date':'2012-04-18', 'Time_Bucket':180},
                    {'Instrument':'AAA', 'Date':'2012-04-18', 'Time_Bucket':100},
                    {'Instrument':'AAA', 'Date':'2012-04-18', 'Time_Bucket':67},
                    {'Instrument':'AAA', 'Date':'2012-04-18', 'Time_Bucket':33},
                    {'Instrument':'AAA', 'Date':'2012-04-18', 'Time_Bucket':1},
                    {'Instrument':'AAA', 'Date':'2012-04-19', 'Time_Bucket':175},
                    {'Instrument':'AAA', 'Date':'2012-04-19', 'Time_Bucket':110},
                    {'Instrument':'AAA', 'Date':'2012-04-19', 'Time_Bucket':30},
                    {'Instrument':'AAA', 'Date':'2012-04-19', 'Time_Bucket':1},
                    {'Instrument':'BBB', 'Date':'2012-04-18', 'Time_Bucket':180},
                    {'Instrument':'BBB', 'Date':'2012-04-18', 'Time_Bucket':150},
                    {'Instrument':'BBB', 'Date':'2012-04-18', 'Time_Bucket':10}])

我有上面的DataFrame。我的目标是创建一个大型数据框,其中包含不同日期的所有仪器,Time_Bucket 范围从 180 到 1。意思是,如果我有 100 个日期为 2012-04-18、2012-04-19、2012-05- 的仪器17, 2012-05-18, 2012-08-15, 2012-08-16,然后我需要创建 100*6*180 的总行数,每个单元格按升序标记日期,但 Time_Bucket 的降序。然后,我会将现有的 DataFrame 与这个新创建的 DataFrame 合并,并填写一些数据分析。我只能编写以下代码,但它不起作用:

df = pd.DataFrame({ 'Instrument' : 'AAA', 'BBB', 'CCC'}, 
                   {'Date': '2012-04-18', '2012-04-19', '2012-05-17', '2012-05-18', '2012-08-15', '2012-08-16'}, 
                   {'Time_Bucket': range(180, N-1 ,1))

你能帮忙吗?谢谢。

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

使用itertools.product 并传递给DataFrame 构造函数:

i = ['AAA', 'BBB', 'CCC']
d = ['2012-04-18', '2012-04-19', '2012-05-17', '2012-05-18', '2012-08-15', '2012-08-16']
r = range(180, 0 , -1)

from  itertools import product
df = pd.DataFrame(list(product(i, d, r)), columns=['Instrument','Date','Time_Bucket'])
print (df)
     Instrument        Date  Time_Bucket
0           AAA  2012-04-18          180
1           AAA  2012-04-18          179
2           AAA  2012-04-18          178
3           AAA  2012-04-18          177
4           AAA  2012-04-18          176
        ...         ...          ...
3235        CCC  2012-08-16            5
3236        CCC  2012-08-16            4
3237        CCC  2012-08-16            3
3238        CCC  2012-08-16            2
3239        CCC  2012-08-16            1

[3240 rows x 3 columns]

【讨论】:

  • 如果我想让 Time_Bucket 按升序排列怎么办?我试过 r = range(180, 0 , 1) 但它不起作用。非常感谢。
  • @ShaunLim - 然后使用r = range(1, 181)
  • 还有一个问题,有没有办法让 Time_Bucket 用 0 而不是 1 开始?谢谢!
  • @ShaunLim - 当然r = range(0, 181)
猜你喜欢
  • 2018-12-14
  • 2021-12-02
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 2020-08-04
相关资源
最近更新 更多