Rya*_*cis 2 python apply dataframe python-3.x pandas
程序:我有三个功能.函数A,B和C.函数A使用apply()将函数B和C应用于全局Pandas DataFrame.
问题:检查结果表明只有功能B应用于全局数据帧
其他说明:如果我从python解释器应用函数C,那么它的工作原理.
这个问题的三个主要功能是:
load_paypal():将数据加载到全局Pandas DataFrame中,并将其他两个函数应用于几列.
read_cash():读取值,删除美元符号,逗号等并返回一个数字
read_date():读取一个字符串并返回一个日期时间.
我遇到的问题是,当我使用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
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
注意:ryan_tools只是我常用的有用函数的一般文件
.apply() 不是就地操作(即,它返回一个新对象而不是修改原始对象):
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
Run Code Online (Sandbox Code Playgroud)
您可能想要的是将列重新分配给您创建的新列.apply():
paypal_data['Date'] = paypal_data['Date'].apply(ryan_tools.read_date)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3044 次 |
| 最近记录: |