Pandas Apply function not working consistently (Python 3)

Summary

Procedure:
I have three functions. Function A, B, and C. Function A uses apply() to apply function B and C to a global Pandas DataFrame.

Problem:
Inspecting the results shows that only Function B was applied to the global dataframe

Other notes:
If I apply Function C from the python interpreter, then it works.


The long version

The three main functions in this problem are:

load_paypal(): Loads data into a gobal Pandas DataFrame and applies the other two functions on a couple columns.

read_cash(): reads in the value, strips dollar signs, commas etc and returns a number

read_date(): reads a string and returns a datetime.

The problem I’m having is that when I use apply() to apply read_cash, it appears to work but read_date doesn’t. Additionally, when I use the read_date function with apply from the python interpreter, with the exact same code, I get the expected results, ie it works.

Functions

load_paypal

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def load_paypal():
global paypal_data
paypal_data = pd.DataFrame( pd.read_csv(open("Download.csv") ) )
paypal_data = paypal_data.fillna(0)
cash_names = ('Gross', 'Fee', 'Net', 'Shipping and Handling Amount', 'Sales Tax', 'Balance')
for names in cash_names:
paypal_data[names].apply( ryan_tools.read_cash )
paypal_data = paypal_data.rename(columns = { paypal_data.columns[0] : 'Date'})
paypal_data['Date'].apply( ryan_tools.read_date )
print( paypal_data['Date'] ) # The 'Date' datatype is still a string here
print( paypal_data['Net'] ) # The 'Net' datatype is proven to be converted
# to a number over here( It definitely starts out as a string )
return
</code>
<code>def load_paypal(): global paypal_data paypal_data = pd.DataFrame( pd.read_csv(open("Download.csv") ) ) paypal_data = paypal_data.fillna(0) cash_names = ('Gross', 'Fee', 'Net', 'Shipping and Handling Amount', 'Sales Tax', 'Balance') for names in cash_names: paypal_data[names].apply( ryan_tools.read_cash ) paypal_data = paypal_data.rename(columns = { paypal_data.columns[0] : 'Date'}) paypal_data['Date'].apply( ryan_tools.read_date ) print( paypal_data['Date'] ) # The 'Date' datatype is still a string here print( paypal_data['Net'] ) # The 'Net' datatype is proven to be converted # to a number over here( It definitely starts out as a string ) return </code>
def load_paypal():
    global paypal_data
    paypal_data = pd.DataFrame( pd.read_csv(open("Download.csv") ) )
    paypal_data = paypal_data.fillna(0)
    cash_names = ('Gross', 'Fee', 'Net', 'Shipping and Handling Amount', 'Sales Tax', 'Balance')

    for names in cash_names:
        paypal_data[names].apply( ryan_tools.read_cash )

    paypal_data = paypal_data.rename(columns = { paypal_data.columns[0] : 'Date'})

    paypal_data['Date'].apply( ryan_tools.read_date )
    print( paypal_data['Date'] ) # The 'Date' datatype is still a string here
    print( paypal_data['Net'] ) # The 'Net' datatype is proven to be converted
    # to a number over here( It definitely starts out as a string )
    return

ryan_tools.read_date

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def read_date(text):
for fmt in ( '%m/%d/%y' , '%M/%D/%y' , '%m/%d/%Y', '%Y/%m/%d', '%Y/%M/%D', 'Report Date :%m/%d/%Y', '%Y%M%D' , '%Y%m%d' ):
try:
return datetime.datetime.strptime(text, fmt)
except ValueError:
pass
raise ValueError('No Valid Date found')
</code>
<code>def read_date(text): for fmt in ( '%m/%d/%y' , '%M/%D/%y' , '%m/%d/%Y', '%Y/%m/%d', '%Y/%M/%D', 'Report Date :%m/%d/%Y', '%Y%M%D' , '%Y%m%d' ): try: return datetime.datetime.strptime(text, fmt) except ValueError: pass raise ValueError('No Valid Date found') </code>
def read_date(text):
    for fmt in ( '%m/%d/%y' , '%M/%D/%y' , '%m/%d/%Y', '%Y/%m/%d', '%Y/%M/%D', 'Report Date :%m/%d/%Y', '%Y%M%D' , '%Y%m%d' ):
        try:
            return datetime.datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('No Valid Date found')

ryan_tools.read_cash

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def read_cash(text):
text = str(text)
if text == '':
return 0
temp = text.replace(' ', '')
temp = text.replace(',', '')
temp = temp.replace('$', '')
if ('(' in temp or ')' in temp):
temp = temp.replace('(', '')
temp = temp.replace(')', '')
ans = float(temp) * -1.0
return ans
ans = round(float(temp),2)
return ans
</code>
<code>def read_cash(text): text = str(text) if text == '': return 0 temp = text.replace(' ', '') temp = text.replace(',', '') temp = temp.replace('$', '') if ('(' in temp or ')' in temp): temp = temp.replace('(', '') temp = temp.replace(')', '') ans = float(temp) * -1.0 return ans ans = round(float(temp),2) return ans </code>
def read_cash(text):
    text = str(text)
    if text == '':
        return 0
    temp = text.replace(' ', '')
    temp = text.replace(',', '')
    temp = temp.replace('$', '')

    if ('(' in temp or ')' in temp):
        temp = temp.replace('(', '')
        temp = temp.replace(')', '')
        ans = float(temp) * -1.0
        return ans
    ans = round(float(temp),2)

    return ans

Notes: ryan_tools is just my general file of commonly used useful functions

.apply() is not an in-place operation(i.e., it returns a new object rather than modifying the original):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>In [3]: df = pd.DataFrame(np.arange(10).reshape(2,5))
In [4]: df
Out[4]:
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
In [5]: df[4].apply(lambda x: x+100)
Out[5]:
0 104
1 109
Name: 4, dtype: int64
In [6]: df
Out[6]:
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
</code>
<code>In [3]: df = pd.DataFrame(np.arange(10).reshape(2,5)) In [4]: df Out[4]: 0 1 2 3 4 0 0 1 2 3 4 1 5 6 7 8 9 In [5]: df[4].apply(lambda x: x+100) Out[5]: 0 104 1 109 Name: 4, dtype: int64 In [6]: df Out[6]: 0 1 2 3 4 0 0 1 2 3 4 1 5 6 7 8 9 </code>
In [3]: df = pd.DataFrame(np.arange(10).reshape(2,5))

In [4]: df
Out[4]:
   0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9

In [5]: df[4].apply(lambda x: x+100)
Out[5]:
0    104
1    109
Name: 4, dtype: int64

In [6]: df
Out[6]:
   0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9

What you probably want is to reassign the column to the new one created by your .apply():

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date)
</code>
<code>paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date) </code>
paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date)

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật