python - 迭代数据框

标签 python pandas dataframe

我以这个数据框为例:

import pandas as pd
df = pd.DataFrame({'country':['china','canda','usa' ], 'value':[1000, 850, 1100], 'fact':[1000,200,850]})
df.index=df['country']
df = df.drop('country', axis=1)

我想迭代每个国家/地区的 GDP,并在本次迭代中创建一个新列,该列将根据条件函数充满 1 或 0:

for x in df['value']:
    if x > 900:
        df['answer']=1
    else:
        df['answer']=0

我期望一列包含以下值:

[1,0,1]

因为加拿大的数值低于 900。

但是我有一栏充满了。

出了什么问题?

最佳答案

使用np.where

df["answer"] = np.where(df["value"]> 900, 1,0)

或者

df["answer"] = (df["value"]> 900).astype(int)

输出:

         value  fact    answer
country         
china     1000  1000    1
canda     850   200     0
usa       1100  850     1

你的代码有什么问题

当您执行 df['answer']=1 时,表达式会将 1 分配给 answer 列中的所有行。

因此最后评估的值被分配给该列

关于python - 迭代数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134053/

相关文章:

python - 如何从每个一级指标中最大的二级指标的单元格中取值?

python - 在列表python中拆分Mac地址

R 在搜索模式中使用 NA 选择数据帧行

python - 如何在 Python 中使用带前缀的 str.get_dummies?

python - Python 3.2 txt 中不区分大小写

python - 寻找两个圆的交点

python - 当打印包裹在 pandas 对象中的自定义对象时,我需要从 __repr__ 返回什么才能有多行

python - Bokeh - Pandas 无法从 JS 读取 excel 文件的 bytesIO 对象

python - 属性错误 : 'DataFrame' object has no attribute 'group'

python - 从终端运行脚本时 Altair 不显示图表?