gpt4 book ai didi

python - 使用 Pandas DataFrame 进行迭代并更改值

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:56 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,我想根据行中的值为每一行分配一个随机数,并写出一个数据框。

所以我正在尝试:

for index, row in person[person['AGE_R'] == 1].iterrows():
row = index, random.randint(1, 15)

但我不太清楚如何从中写出数据帧(不可能?)。我能够得到一个元组列表,我可以将其合并为可行的格式,但我确信有更好的方法。

我之前尝试过:

person[person['AGE_R'] == 1] = random.randint(1, 15)

但这会将 'AGE_R 的所有 1 设置为 randint 的值。有用,但不是我想要的。

有什么建议吗?

谢谢!

最佳答案

如果你想进行向量化运算,可以使用numpy.random.randint:

>>> df = pd.DataFrame({'AGE_R':[1,2,3,5,4,3,1]})
>>> df
AGE_R
0 1
1 2
2 3
3 5
4 4
5 3
6 1
>>> df.ix[df['AGE_R'] == 1, 'AGE_R'] = np.random.randint(1, 15, len(df[df['AGE_R'] == 1]))
>>> df
AGE_R
0 5
1 2
2 3
3 5
4 4
5 3
6 11

或者您可以使用应用:

>>> df.ix[df['AGE_R'] == 1, 'AGE_R'] = df.ix[df['AGE_R'] == 1].apply(lambda x: np.random.randint(1, 15), axis = 1)
>>> df
AGE_R
0 5
1 2
2 3
3 5
4 4
5 3
6 12

关于python - 使用 Pandas DataFrame 进行迭代并更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19737194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com