熊猫:用数据填充随机的空行

时间:2018-06-29 14:43:50

标签: python-3.x pandas random

我有一个带有几个当前为空列的数据框。我希望其中的一部分填充从正态分布中提取的数据,而其余所有部分都留空。因此,例如,如果60%的元素应为空白,则60%为空白,而其他40%将被填充。我已经通过numpy具有正态分布,但是我试图弄清楚如何选择随机行来填充。目前,我唯一想到的方法是使用FOR循环,而我宁愿避免这种情况。

有人对我如何随机填充数据框的空白元素有任何想法吗?我下面有一些代码,用于随机数。

data.loc[data['ColumnA'] == 'B', 'ColumnC'] = np.random.normal(1000, 500, rowsB).astype('int64')

1 个答案:

答案 0 :(得分:1)

piRSquared的建议很好。我们只剩下要解决的问题了。 刚看过一些最新的未解决的熊猫问题,情况就更糟了。

import pandas as pd
import numpy as np

#some redundancy here as i make an empty dataframe -pretending i start like you with a Dataframe.
df = pd.DataFrame(index = range(11),columns=list('abcdefg'))
num_cells = np.product(df.shape)

# make a 2-dim array with number from 1 to number cells.
arr =np.arange(1,num_cells+1)

#inplace shuffle - this is the key randomization operation
np.random.shuffle(arr)   

arr = arr.reshape(df.shape) 

#place the shuffled values, normalized to the number of cells, into my dateframe.
df = pd.DataFrame(index = df.index,columns = df.columns,data=arr/np.float(num_cells))

#use applymap to set keep 40% of cells as ones, the other 60% as nan.
df = df.applymap(lambda x: 1 if x > 0.6 else np.nan)

# now sample a full set from normal distribution
# but when multiplying the nans will cause the sampled value to nullify, whilst the multiply by 1 will retain the sample value.
df * np.random.normal(1000,500,df.shape)

因此,您剩下的随机40%的单元格包含正态分布的平局。

enter image description here

如果数据帧很大,则可以假定统一rand()函数的稳定性。在这里,我没有这样做,而是明确确定了在阈值之上和之下有多少个单元格。

相关问题