pandas 根据其他列更改列值
pandas change column value based on other column
我正在尝试使用 [tranches_age] 列中定义的范围内的随机数更改 [age] 值
index
age
tranches_age
1
NaN
80-85
2
NaN
70-75
3
NaN
30-35
使用apply
df = pd.DataFrame([
[1, None, '80-85'],
[2, None, '70-75'],
[3, None, '30-35']],
columns=['index', 'age', 'tranches_age']
)
def transform(x):
agemin, agemax = map(int, x.split('-'))
return random.randint(agemin, agemax)
df['age'] = df['tranches_age'].apply(transform)
应该输出类似
的东西
index age tranches_age
0 1 85 80-85
1 2 71 70-75
2 3 35 30-35
等等
计算范围的min
和width
,然后使用(min + width*np.random.random())
生成随机数。
我们可以对这些操作进行矢量化处理,从而可能获得更好的性能。
使用:
min_r = df.tranches_age.str[:2].astype(int)
widths = df.tranches_age.str[3:].astype(int) - min_r
df['age'] = (min_r + widths* np.random.random(size=(widths.shape[0]))).astype(int)
输出:
>>> df
index age tranches_age
0 1 82 80-85
1 2 70 70-75
2 3 31 30-35
试试 numpy
random.randint
df['new'] = df['tranches_age'].apply(lambda x : np.random.randint(low=x.split('-')[0],high=x.split('-')[1]))
0 83
1 72
2 32
Name: tranches_age, dtype: int64
我正在尝试使用 [tranches_age] 列中定义的范围内的随机数更改 [age] 值
index | age | tranches_age |
---|---|---|
1 | NaN | 80-85 |
2 | NaN | 70-75 |
3 | NaN | 30-35 |
使用apply
df = pd.DataFrame([
[1, None, '80-85'],
[2, None, '70-75'],
[3, None, '30-35']],
columns=['index', 'age', 'tranches_age']
)
def transform(x):
agemin, agemax = map(int, x.split('-'))
return random.randint(agemin, agemax)
df['age'] = df['tranches_age'].apply(transform)
应该输出类似
的东西 index age tranches_age
0 1 85 80-85
1 2 71 70-75
2 3 35 30-35
等等
计算范围的min
和width
,然后使用(min + width*np.random.random())
生成随机数。
我们可以对这些操作进行矢量化处理,从而可能获得更好的性能。
使用:
min_r = df.tranches_age.str[:2].astype(int)
widths = df.tranches_age.str[3:].astype(int) - min_r
df['age'] = (min_r + widths* np.random.random(size=(widths.shape[0]))).astype(int)
输出:
>>> df
index age tranches_age
0 1 82 80-85
1 2 70 70-75
2 3 31 30-35
试试 numpy
random.randint
df['new'] = df['tranches_age'].apply(lambda x : np.random.randint(low=x.split('-')[0],high=x.split('-')[1]))
0 83
1 72
2 32
Name: tranches_age, dtype: int64