[英]Merging a list of dataframes with different lengths and columns in python
我有 100 个数据帧的列表,我试图将它们合并到一个数据帧中,但无法这样做。 所有数据帧都有不同的列并且长度不同。 为了提供一些上下文和背景,每个数据帧包含 4 个情绪分数(使用 VaderSentiment 计算)。 数据框具有以下表示形式:
用户 1 数据帧
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 |
用户 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 |
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 |
所有数据帧都有一列共同的,即created_at 。 我想要实现的是合并基于created_at列的所有数据帧,这样我只能从所有其他数据帧中获得一个 created_at列和所有其他列。 结果应该有 **400* 列的情绪分数以及created_at列。
我的代码如下:
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)
问题是,当我运行上面的代码时,我得到了所需的列排列,但是我没有得到所有值中的 NaN 值,因此基本上有一个包含 401 列的数据框,其中只有created_at列包含价值观
任何和所有的帮助表示赞赏。
谢谢
编辑
我已经尝试了各种不同的解决方案来解决这里发布的不同问题,但它们似乎都不起作用,因此作为最后的手段,我开始了这个线程
编辑 2
我可能已经想出了解决我的问题的方法。 使用下面的代码,我可以将所有列附加到frames
。 但是,这会创建created_at列的副本,该列恰好是object类型。 如果我可以将所有日期合并为一列,那么我的麻烦就离解决更近了。
for f in allFiles :
file = open(f, 'r')
count=count+1
_, fname = os.path.split(f)
df = pd.read_csv(f)
dates = df.iloc[:,0]
neut = df.iloc[:,1]
pos = df.iloc[:,2]
neg = df.iloc[:,3]
comp = df.iloc[:,4]
all_frames.append(dates)
all_frames.append(neut)
all_frames.append(pos)
all_frames.append(neg)
all_frames.append(comp)
frame = pd.concat(all_frames,axis=1)
任何帮助,将不胜感激
我强烈建议你修改你的数据模型。 拥有这么多列通常表示出现问题。 话虽如此,这是一种方法。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.