Pandas数据帧附加数据帧(多列/行+多列、单行)

2024-09-30 10:34:18 发布

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

数据帧中的更多冒险:)

所以,我几乎已经掌握了所有的基本知识,然而,这一点让我感到困惑。我有两个数据帧(下图)。第一个(techIndicator)有大量的列和行,所有列和行都正确填充。第二个数据帧(社交)有多个列,但只有一行

我需要添加列(按照SS工作),但我想复制social dataframe的行,一直复制到“填充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)

Main dataframe: techIndicator

Dataframe to append


Tags: 数据falsetrueindexsocialsortlongpd
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:18

因此,我为您提供了一个解决方案,它不使用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

相关问题 更多 >

    热门问题