使用Series.apply时Pandas/Arrow行为不符预期的原因咨询
The core issue here is how you're passing the Arrow format method to Pandas' apply function—your first approach uses an unbound class method, which leads to unexpected parameter handling, while your loop correctly calls the instance method directly.
Let's Break Down the Problem
When you write:
ym = dt.apply(arrow.arrow.Arrow.format,'MMM-YY')
You're passing the unbound format method from Arrow's internal arrow.arrow.Arrow class to apply. Pandas' apply will pass each Arrow instance from your Series as the first argument to this method. While in theory arrow.Arrow.format(row, 'MMM-YY') should be equivalent to row.format('MMM-YY'), there are two key issues here:
- You're referencing an internal class (
arrow.arrow.Arrow) instead of the publicarrow.Arrowclass, which can lead to inconsistent behavior. - Even with the correct class reference, unbound methods don't play nicely with Pandas'
applyparameter logic—instead of returning the formatted string, the call ends up returning the original Arrow object's default string representation.
Your loop works because you're directly calling the format instance method on each Arrow object, which correctly accepts the 'MMM-YY' format string as its argument.
Fixes to Get Consistent Results
There are two simple ways to adjust your apply code to match the loop's output:
1. Use a Lambda Function to Wrap the Instance Method
This makes parameter passing explicit and avoids issues with unbound methods:
srs = pd.Series(['2016-10-02T00:24:15.707Z','2016-10-02T00:24:27.294Z','2016-10-02T01:15:56.682Z']) dt = srs.apply(arrow.get, tz="Europe/Paris") ym = dt.apply(lambda x: x.format('MMM-YY')) print(ym)
2. Pass the Method Name Directly to apply
Pandas allows you to pass a string method name when working with object-based Series—this automatically calls the method on each element and passes any additional arguments:
ym = dt.apply('format', 'MMM-YY')
Either approach will produce the expected output:
0 Oct-16 1 Oct-16 2 Oct-16 dtype: object
Is This a Bug?
No, this isn't a bug—it's just a mismatch between how unbound class methods work and how you expected Pandas' apply to handle them. Using instance methods directly (via lambda or method name string) is the intended way to perform this kind of operation.
内容的提问来源于stack exchange,提问作者seanysull

