mit*_*tsi 9 python numpy missing-data pandas
如何np.nan在DataFrame中随机插入?假设我想在DataFrame中使用10%的空值.
我的数据如下:
df = pd.DataFrame(np.random.randn(5, 3),
index=['a', 'b', 'c', 'd', 'e'],
columns=['one', 'two', 'three'])
one two three
a 0.695132 1.044791 -1.059536
b -1.075105 0.825776 1.899795
c -0.678980 0.051959 -0.691405
d -0.182928 1.455268 -1.032353
e 0.205094 0.714192 -0.938242
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法来插入空值?
Kod*_*ist 16
这里有一种方法可以准确地清除10%的单元格(或者更确切地说,现有数据框架的大小可以达到接近10%).
import random
ix = [(row, col) for row in range(df.shape[0]) for col in range(df.shape[1])]
for row, col in random.sample(ix, int(round(.1*len(ix)))):
df.iat[row, col] = np.nan
Run Code Online (Sandbox Code Playgroud)
这是一种独立清除细胞的方法,每细胞概率为10%.
df = df.mask(np.random.random(df.shape) < .1)
Run Code Online (Sandbox Code Playgroud)
我认为您可以轻松地遍历数据框列并将NaN值分配给pandas.DataFrame.sample()方法生成的每个单元格。
代码如下。
for col in df.columns:
df.loc[df.sample(frac=0.1).index, col] = pd.np.nan
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5580 次 |
| 最近记录: |