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

标签 python csv pandas

我有一个 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/

相关文章:

python - 如何为 Pandas 中数据帧的给定列中的每个唯一组件创建一个新列?

python - OpenCV - 在捕获循环中没有 waitkey 不显示图像

python - 使用python在html源代码中查找图像

python - ValueError 尝试遍历

vba - Excel VBA打开对话框导入csv

python - 更改 Seaborn 应用调色板的轴

python - 将 df reshape 为多索引并沿键连接

python - 获取多个日期时间对的日期范围

python - 如何将结果从 Multiprocessing.Pool 流式传输到 csv?

python - 数据框中连续天数的平均值