[英]How to apply a concat function to a group by data frame using pandas?
Code 1: 代码1:
df = pd.read_csv("example.csv", parse_dates=['d'])
df2 = df.set_index(['d', 'c'])
df3 = df2.groupby(level=['c'])
def function(x):
a = pd.rolling_mean(x, 3).rename(columns = {'b':'rm'})
c = pd.rolling_std(x, 3).rename(columns = {'b':'rsd'})
pd.concat([x, a, c], axis=1)
df4 = df3.apply(lambda x: function(x))
Code 2: 代码2:
df = pd.read_csv("example.csv", parse_dates=['d'])
df2 = df.set_index(['d', 'c'])
df3 = df2.groupby(level=['c'])
def function(x):
x.assign(rm = lambda x: pd.rolling_mean(x, 3))
df4 = df3.apply(lambda x: function(x))
Output of df4.head() in both of the above code1 AND code 2 is a square in iPython?? 在上述两个代码1和代码2中df4.head()的输出在iPython中是一个正方形? I can't figure out why. 我不知道为什么。
Output: 输出:
What df3 looks like: df3是什么样的:
What df looks like: df看起来像什么:
You're missing a return statement: 您缺少返回声明:
In [11]: def function(x):
a = pd.rolling_mean(x, 3).rename(columns = {'bookings':'rm'})
c = pd.rolling_std(x, 3).rename(columns = {'bookings':'rsd'})
return pd.concat([x, a, c], axis=1)
In [12]: df3.apply(lambda x: function(x))
Out[12]:
bookings rm rsd
ds city
2013-01-01 City_2 69 NaN NaN
2013-01-02 City_2 101 NaN NaN
2013-01-03 City_2 134 101.333333 32.501282
2013-01-04 City_2 155 130.000000 27.221315
2013-01-05 City_2 104 131.000000 25.632011
2013-01-06 City_2 121 126.666667 25.967929
2013-01-07 City_2 143 122.666667 19.553346
2013-01-08 City_2 173 145.666667 26.102363
2013-01-09 City_2 142 152.666667 17.616280
2013-01-10 City_2 154 156.333333 15.631165
2013-01-11 City_2 139 145.000000 7.937254
Without the return function
was returning None, hence the empty DataFrame (which was rendered by ipython as a square - which may be a bug). 如果没有return function
则返回None,因此返回一个空的DataFrame(由ipython渲染为正方形-可能是一个错误)。
In [13]: df3.apply(lambda x: None)
Out[13]:
Empty DataFrame
Columns: []
Index: []
Note: In some languages (eg Ruby, Julia, Scala) the last line is returned without being explicit with the return. 注意:在某些语言(例如Ruby,Julia,Scala)中,返回的最后一行没有在返回时明确显示。 In Python if you miss out the return statement the function returns None. 在Python中,如果错过了return语句,该函数将返回None。
In [21]: def foo():
1
In [22]: foo() == None
Out[22]: True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.