我有一个数据帧,它包含一些开始和结束日期,我想逐行传递给函数,即成对的开始和结束日期。
Data
start | end
2015-06-01 2016-06-28
.
.
.我希望能够将数据帧的整行或某些列从数据帧传递给函数,并且该函数分别对所有行进行重复。
我只能让pandas中的.apply和.applymap处理数据帧中的单个列,而不能处理数据帧中的多个或所有列(或者只是传递给函数的列数)。
发布于 2016-06-04 11:04:42
如果只是遍历这些行,则应该使用iterrows
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
In [12]: df
Out[12]:
A B
0 1 2
1 3 4
In [13]: for i, row in df.iterrows():
print(row)
A 1
B 2
Name: 0, dtype: int64
A 3
B 4
Name: 1, dtype: int64可以使用[[...]]将其限制为某些列
In [14]: df[["A"]]
Out[14]:
A
0 1
1 3可以通过传递axis=1对行而不是列使用apply
In [21]: df.apply(lambda row: row.sum(), axis=1)
Out[21]:
0 3
1 7
dtype: int64注意:在这种情况下,您可以使用原生pandas sum函数,但在编写您自己的函数时,它们可以接受一行(作为Series):
In [31]: df.sum(axis=1) # much faster
Out[31]:
0 3
1 7
dtype: int64
In [32]: df.apply(print, axis=1) # python 3 (print is a function)
A 1
B 2
Name: 0, dtype: int64
A 3
B 4
Name: 1, dtype: int64
Out[32]:
0 None
1 None
dtype: objecthttps://stackoverflow.com/questions/37625683
复制相似问题