【问题标题】:Pandas Dataframe - Append dataframes (Multiple columns/rows + Multiple columns, single row)Pandas Dataframe - 附加数据帧(多列/行 + 多列,单行)
【发布时间】:2020-07-23 11:24:56
【问题描述】:

数据框的更多冒险:)

所以,我几乎掌握了所有的基础知识,但是,这个让我难过。我有两个数据框(下图)。第一个(techIndicator)有大量的列和行,都正确填充。第二个数据框(社交)有多列,但只有一行。

我需要添加列(按照 SS 工作),但我想一直复制社交数据框的行以“填写 nan”。

这是我用来将所有数据帧连接成一个数据帧的代码(除了社交之外的所有工作):

techIndicator = pd.concat([inter_day, macd, rsi, ema, vwap, adx, dmi, social], axis = 1)
techIndicator.sort_index(ascending=False, inplace=True)
techIndicator.dropna()
techIndicator.reset_index(drop=True)

根据下面的 SS,前三行应该是这样的:

datetime1 | 1 | 2 | 3 | 4 | ......| 9 | 8| 7 | 6
datetime2 | 2 | 1 | 4 | 3 | ......| 9 | 8| 7 | 6
datetime3 | 3 | 4 | 1 | 2 | ......| 9 | 8| 7 | 6

相反,上面的连接添加了列,但删除了值(我已经检查过数据类型,它们都是 float64 的)

请帮忙 =) 我的 google-fu 不适合这个 >.

在下面 Alex 的帮助下,我能够解决我遇到的许多问题!

    dfTemp = pd.concat([inter_day, macd, rsi, ema, vwap, adx, dmi], axis = 1)
    dfTemp.sort_index(ascending=False, inplace=True)
    dfTemp.dropna()
    dfTemp.reset_index(inplace = True)
    

    long_social = social
    for a in range(dfTemp.shape[0] - 1):
        long_social=pd.concat([long_social, social])
    long_social.reset_index(inplace = True)
    long_social.drop(columns = ['index'], inplace = True)
    
    techIndicator = pd.concat([dfTemp, long_social], axis = 1)
    techIndicator.rename(columns={'date': 'Date',
                                  '1. open': 'Open',
                                  '2. high': 'High',
                                  '3. low': 'Low',
                                  '4. close': 'Close',
                                  '5. volume': 'Volume',
                                  'DX': 'DMI'}, inplace=True)

    techIndicator.dropna(inplace=True)
    techIndicator.reset_index(drop=True, inplace=True)
    techIndicator.set_index('Date', inplace=True)
    techIndicator.sort_index(ascending=False, inplace=True)

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    所以我为您提供了一个解决方案,它不使用 concat 将列添加到您的主数据集,但它可以完成工作。

    它的流程是因为两个数据框大小不均匀,我们使它们大小均匀,然后循环通过命名它们来添加列。

    # first create a copy of your social_df which we will append it to for as long as your main df is
    
    long_soial=social_df
    
    for a in range(main_df.shape[0]):
        social_long=pd.concat([social_long, social])
    
    # now you have a long_social_df with the same length as your main df
    
    social_vars=list(social.columns)  # Get the column names from social for naming them as we add to the main df
    
    for i, var in enumerate(social_vars):
        main_df[var]=list[social_long[i] # add the columns by creating a new empty column with the desired name and adding the social info as a list to the named column
    

    【讨论】:

    • 谢谢亚历克斯!我能够调整您的代码以填充行,并且我还发现了其他一些正在发生的错误。我将发布完整的工作代码。
    • 太棒了!我很高兴看到你让它按照你想要的方式运行。希望你能从数据中得到一些很酷的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2014-05-19
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多