在python中合并具有不同长度和列的数据框列表

时间:2019-08-14 16:12:20

标签: python pandas list dataframe merge

我有100个数据框的列表,我试图将其合并为一个数据框,但无法这样做。所有数据帧都有不同的列,并且长度不同。为了提供一些背景和背景信息,每个数据框均包含4个情感评分(使用VaderSentiment计算)。数据框具有以下表示形式:

用户1数据框

import openSocket from 'socket.io-client';

let url = Store.config.socketserverurl + ":" + Store.config.socketserverport;
const socket = openSocket.connect(url);

用户2数据框

created_at       | positive score of user 1 tweets  |  negative score of user 1   tweets|    neutral score of user 1 tweets  | compound score of user 1 tweets |
23/2/2011 10:00  |           1.12                   |            1.3                    |                1.0                 |                  3.3            |
24/2/2011 11:00  |           1.20                   |            1.1                    |                0.9                 |                  2.5            |

所有数据框的共同点是一个列,即 created_at 。我想要实现的是基于 created_at 列合并所有数据框,这样我只能从所有其他数据框中仅 created_at 列和所有其他列。结果应具有** 400 *的情感得分列以及 created_at 列。

我的代码如下:

created_at       | positive score of user 1 tweets  |  negative score of user 1   tweets|    neutral score of user 1 tweets  | compound score of user 1 tweets |
25/3/2011 23:00  |           0.12                   |            1.1                    |                0.1                 |                  1.1            |
26/3/2011 08:00  |           1.40                   |            1.5                    |                0.4                 |                  1.5            |
01/4/2011 19:00  |           1.80                   |            0.1                    |                1.9                 |                  3.9            |

问题是,当我如上所述运行代码时,我得到了所需的列排列方式,但是我没有获得值,而是在所有值中都获得了NaN,因此实际上具有一个包含401列的数据框,其中只有 created_at 列包含值

感谢您的帮助。

谢谢

编辑

我针对此处发布的不同问题尝试了各种不同的解决方案,但似乎都没有效果,因此,作为最后的选择,我启动了此主题

编辑2

我也许想出了解决我问题的方法。使用下面的代码,我可以将所有列附加到import pandas as pd import glob import numpy as np import os from functools import reduce path = r'C:\Users\Desktop\Tweets' allFiles = glob.glob(path + "/*.csv") list = [] frame = pd.DataFrame() count=0 for f in allFiles: file = open(f, 'r') count=count+1 _, fname = os.path.split(f) df = pd.read_csv(f) #print(df) list.append(df) frame = pd.concat(list) print(frame) 中。但是,这会创建 created_at 列的重复,该列恰好是 object 类型。如果我可以将所有日期合并到一栏中,那么我的麻烦就更接近解决了。

frames

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我强烈建议您修改数据模型。拥有那么多列通常表明存在错误。话虽如此,这是一种方法。 list也是内置数据类型。不要用变量名覆盖它。

我认为除了created_at之外,每个文件中的列都是唯一的。

all_frames = []
for f in allFiles:
    file = open(f, 'r')
    count=count+1
    _, fname = os.path.split(f)
    df = pd.read_csv(f, parse_dates=['created_at'], index_col='created_at')
    all_frames.append(df)

# This will create a dataframe of size n * 400
# n is the total number of rows between all files
frame = pd.concat(all_frames, join='outer', copy=False, sort=False)

# If you want to line up the hour across all users
frame.groupby(level=0)[frame.columns].first()
相关问题