col1是一列独立的值,col2是基于“国家和类型”组合的汇总.我想使用以下逻辑来计算col3到col5列:
> col3:col1中的元素与col1的总数之比
> col4:col1中的元素与col2中相应元素的比率
> col5:col3和col4中按行元素乘积的自然指数
我写了下面的函数来实现这个目的:
def calculate(df):
for i in range(len(df)):
df['col3'].loc[i] = df['col1'].loc[i]/sum(df['col1'])
df['col4'].loc[i] = df['col1'].loc[i]/df['col2'].loc[i]
df['col5'].loc[i] = np.exp(df['col3'].loc[i]*df['col4'].loc[i])
return df
该函数会执行,并给我预期的结果,但是笔记本还会引发警告:
SettingWithcopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation:
07001
我不确定是否在这里编写最佳功能.任何帮助,将不胜感激!谢谢.
解决方法:
我认为最好避免在熊猫中应用和循环,因此更好,更快地使用虚拟化解决方案:
df = pd.DataFrame({'col1':[4,5,4,5,5,4],
'col2':[7,8,9,4,2,3],
'col3':[1,3,5,7,1,0],
'col4':[5,3,6,9,2,4],
'col5':[1,4,3,4,0,4]})
print (df)
col1 col2 col3 col4 col5
0 4 7 1 5 1
1 5 8 3 3 4
2 4 9 5 6 3
3 5 4 7 9 4
4 5 2 1 2 0
5 4 3 0 4 4
df['col3'] = df['col1']/(df['col1']).sum()
df['col4'] = df['col1']/df['col2']
df['col5'] = np.exp(df['col3']*df['col4'])
print (df)
col1 col2 col3 col4 col5
0 4 7 0.148148 0.571429 1.088343
1 5 8 0.185185 0.625000 1.122705
2 4 9 0.148148 0.444444 1.068060
3 5 4 0.185185 1.250000 1.260466
4 5 2 0.185185 2.500000 1.588774
5 4 3 0.148148 1.333333 1.218391
时间:
df = pd.DataFrame({'col1':[4,5,4,5,5,4],
'col2':[7,8,9,4,2,3],
'col3':[1,3,5,7,1,0],
'col4':[5,3,6,9,2,4],
'col5':[1,4,3,4,0,4]})
#print (df)
#6000 rows
df = pd.concat([df] * 1000, ignore_index=True)
In [211]: %%timeit
...: df['col3'] = df['col1']/(df['col1']).sum()
...: df['col4'] = df['col1']/df['col2']
...: df['col5'] = np.exp(df['col3']*df['col4'])
...:
1.49 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
不幸的是,对于此示例,循环解决方案的速度确实很慢,因此仅在60行DataFrame中进行了测试:
#60 rows
df = pd.concat([df] * 10, ignore_index=True)
In [3]: %%timeit
...: (calculate(df))
...:
C:\Anaconda3\lib\site-packages\pandas\core\indexing.py:194: SettingWithcopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
10.2 s ± 410 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)