向 Pandas 数据帧中的每个单元格添加不同的随机数 [英] add a different random number to every cell in a pandas dataframe

查看:50
本文介绍了向 Pandas 数据帧中的每个单元格添加不同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的数据添加一些噪音",因此我想为我的 Pandas 数据框中的每个单元格添加一个不同的随机数.此代码有效,但似乎不符合 Python 标准.有没有更好的办法?

I need to add some 'noise' to my data, so I would like to add a different random number to every cell in my pandas dataframe. This code works, but seems unpythonic. Is there a better way?

import pandas as pd
import numpy as np
df = pd.DataFrame(0.0, index=[1,2,3,4,5], columns=list('ABC') )
print df
for x,line in df.iterrows():
  for col in df:
     line[col] = line[col] + (np.random.rand()-0.5)/1000.0
 print df

推荐答案

df + np.random.rand(*df.shape) / 10000.0

让我们使用 应用地图:

Let's use applymap:

df = pd.DataFrame(1.0, index=[1,2,3,4,5], columns=list('ABC') )

df.applymap(lambda x: x + np.random.rand()/10000.0)

输出:

                                                   A  \
1  [[1.00006953418, 1.00009164785, 1.00003177706]...   
2  [[1.00007291245, 1.00004186046, 1.00006935173]...   
3  [[1.00000490127, 1.0000633115, 1.00004117181],...   
4  [[1.00007159622, 1.0000559506, 1.00007038891],...   
5  [[1.00000980335, 1.00004760836, 1.00004214422]...   

                                                   B  \
1  [[1.00000320322, 1.00006981682, 1.00008912557]...   
2  [[1.00007443802, 1.00009270815, 1.00007225764]...   
3  [[1.00001371778, 1.00001512412, 1.00007986851]...   
4  [[1.00005883343, 1.00007936509, 1.00009523334]...   
5  [[1.00009329606, 1.00003174878, 1.00006187704]...   

                                                   C  
1  [[1.00005894836, 1.00006592776, 1.0000171843],...  
2  [[1.00009085391, 1.00006606979, 1.00001755092]...  
3  [[1.00009736701, 1.00007240762, 1.00004558753]...  
4  [[1.00003981393, 1.00007505714, 1.00007209959]...  
5  [[1.0000031608, 1.00009372917, 1.00001960112],...  

这篇关于向 Pandas 数据帧中的每个单元格添加不同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆