使用pandas的groupby和pd.concat一起将行添加到列中

3

我有一个包含约20年数据的大型数据框。我想按年对此数据框进行分组,然后向每个组添加相同的新X值集合。我不知道如何使用pd.concat和groupby。我该如何同时使用pd.concat和df.groupby?

以下是我的数据框子集(我删除了一堆行只是为了显示我想要按年份分组的多个年份)。

my data frame: 
     XSNO    YEAR     X     Z
5     LOL001  1978   0.22 -0.44
6     LOL001  1978   0.95 -0.55
7     LOL001  1978   1.70 -1.01
8     LOL001  1978   2.10 -1.22
9     LOL001  1978   2.68 -1.34
10    LOL001  1978   3.27 -1.41
48    LOL001  1978  17.60 -1.86
49    LOL001  1978  18.21 -1.77
50    LOL001  1978  18.41 -1.65
51    LOL001  1978  18.67 -1.54
52    LOL001  1978  19.00 -1.5
68    LOL001  1978  23.60 -0.31
78    LOL001  1980   0.40 -0.56
79    LOL001  1980   1.50 -0.91
80    LOL001  1980   2.50 -1.25
81    LOL001  1980   3.20 -1.43
82    LOL001  1980   3.90 -1.44
83    LOL001  1980   4.50 -1.55
84    LOL001  1980   5.80 -1.22
101   LOL001  1980  21.50 -0.96
102   LOL001  1980  22.50 -0.69
103   LOL001  1980  23.60 -0.43
104   LOL001  1980  25.10 -0.09
107   LOL001  1981   0.30 -0.40
108   LOL001  1981   0.60 -0.56
109   LOL001  1981   2.40 -1.20
110   LOL001  1981   4.40 -1.34
111   LOL001  1981   7.00 -1.10
112   LOL001  1981   8.60 -1.49

What I would like the output to be (just a subset of the added values for one year):
XSNO    YEAR    X      Z
LOL004  1978    0     NaN
LOL003  1978    0.05  NaN
LOL002  1978    0.1   NaN
LOL001  1978    0.15  NaN
LOL000  1978    0.2   NaN
LOL001  1978    0.22  -0.44
LOL002  1978    0.25  NaN
LOL003  1978    0.3   NaN
LOL004  1978    0.35  NaN
LOL005  1978    0.4   NaN
LOL006  1978    0.45  NaN
LOL007  1978    0.5   NaN
LOL008  1978    0.55  NaN
LOL009  1978    0.6   NaN
LOL010  1978    0.65  NaN
LOL011  1978    0.7   NaN
LOL012  1978    0.75  NaN
LOL013  1978    0.8   NaN
LOL014  1978    0.85  NaN
LOL001  1978    0.95  -0.55


max = df.X.max()
x = np.arange(0, max, 0.05)
x = pd.DataFrame({'X': x})

concat_df = df.groupby(['YEAR']).apply(lambda x: x.concat([df1, x]))
# this doesn't work and gives me an error

concat = pd.concat([df1, x])
# this doesn't give me what I want, it just tacks all the 'x' values (new values) on at the end.  

我不确定如何在分组的pandas数据框中使用merge/join/concat函数。我似乎找不到其他与我所寻找的相同的问题/答案。


1
pd.concat() 就像 .append(),它只是将新数据添加到第一个 dataframe 的末尾。 - BeanBagTheCat
1
没问题。更好的方法是创建一个包含您要查找的x值以及年份值的数据帧,然后使用pd.concat()将该数据帧与原始数据帧连接起来。 - lc93
1个回答

1

这不是解决方案,我只是还不能评论。

应该使用pd.concat 。 另外,您在groupby中的lambda函数使用x作为参数,因此隐藏了x DataFrame。将它们命名为不同的名称,例如:

concat_df = df.groupby(['YEAR']).apply(lambda y: pd.concat([y, x]))

这对我不起作用,您能具体说明一下吗?我不需要两个数据框来连接吗?这就是为什么我使用了pd.concat [df1,x]。我很难理解lambda格式,因此我不明白pd.concat函数中的"y"是在做什么。在我看来,它应该是像这样的:lambda y: pd.concat([y.df,y.x])? - lc93
Lambda函数以groupby生成的组作为参数,因此y是仅包含一年数据的数据帧。当您运行此代码时,是否出现错误或只是不同的输出? - lbd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接