Pandas 应用功能无法始终如一地工作 (Python 3)
Pandas Apply function not working consistently (Python 3)
总结
程序:
我有三个功能。函数 A、B 和 C。函数 A 使用 apply() 将函数 B 和 C 应用于全局 Pandas DataFrame。
问题:
检查结果显示只有函数 B 应用于全局数据帧
其他注意事项:
如果我从 python 解释器应用 Function C,那么它就可以工作。
长版
本题的三个主要函数是:
load_paypal():将数据加载到一个 gobal Pandas DataFrame 并将其他两个函数应用于几个列。
read_cash():读入值,去掉美元符号、逗号等和returns一个数字
read_date():读取字符串和 returns 日期时间。
我遇到的问题是,当我使用 apply() 应用 read_cash 时,它似乎有效,但 read_date 无效。此外,当我将 read_date 函数与来自 python 解释器的 apply 一起使用时,使用完全相同的代码,我得到了预期的结果,即它有效。
函数
load_paypal
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
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
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
注:ryan_tools只是我常用的有用功能的总档
.apply()
不是就地操作(即 returns 一个新对象而不是修改原始对象):
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
您可能想要将该列重新分配给您 .apply()
:
创建的新列
paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date)
总结
程序: 我有三个功能。函数 A、B 和 C。函数 A 使用 apply() 将函数 B 和 C 应用于全局 Pandas DataFrame。
问题: 检查结果显示只有函数 B 应用于全局数据帧
其他注意事项: 如果我从 python 解释器应用 Function C,那么它就可以工作。
长版
本题的三个主要函数是:
load_paypal():将数据加载到一个 gobal Pandas DataFrame 并将其他两个函数应用于几个列。
read_cash():读入值,去掉美元符号、逗号等和returns一个数字
read_date():读取字符串和 returns 日期时间。
我遇到的问题是,当我使用 apply() 应用 read_cash 时,它似乎有效,但 read_date 无效。此外,当我将 read_date 函数与来自 python 解释器的 apply 一起使用时,使用完全相同的代码,我得到了预期的结果,即它有效。
函数
load_paypal
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
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
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
注:ryan_tools只是我常用的有用功能的总档
.apply()
不是就地操作(即 returns 一个新对象而不是修改原始对象):
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
您可能想要将该列重新分配给您 .apply()
:
paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date)