Python:使用.iterrows()创建列

30

我正在尝试使用循环函数创建一个矩阵,该矩阵可以显示一个产品在特定周是否被查看。

df中的每一行(代表一个产品)都有一个close_date(产品关闭的日期)和week_diff(产品列出的周数)。

import pandas
mydata = [{'subid' : 'A', 'Close_date_wk': 25, 'week_diff':3},
          {'subid' : 'B', 'Close_date_wk': 26, 'week_diff':2},
          {'subid' : 'C', 'Close_date_wk': 27, 'week_diff':2},]
df = pandas.DataFrame(mydata)

我的目标是查看每个日期范围内每个产品列出了多少替代产品。

我已经设置了下面的循环:

for index, row in df.iterrows():
    i = 0
    max_range = row['Close_date_wk']    
    min_range = int(row['Close_date_wk'] - row['week_diff'])
    for i in range(min_range,max_range):
        col_head = 'job_week_'  +  str(i)
        row[col_head] = 1

请您帮忙解释一下为什么"row[col_head] = 1"这行既没有添加一列,也没有给该行的该列添加一个值。

比如说,如果:

row A has date range 1,2,3 
row B has date range 2,3  
row C has date range 3,4,5'

理想情况下,我希望最终得到

row A has 0 alternative products in week 1
          1 alternative products in week 2
          2 alternative products in week 3
row B has 1 alternative products in week 2
          2 alternative products in week 3
&c..
2个回答

65

使用row在这里无法改变df以添加新列,您必须引用原始df或使用.loc, .iloc, 或 .ix,例如:

In [29]:

df = pd.DataFrame(columns=list('abc'), data = np.random.randn(5,3))
df
Out[29]:
          a         b         c
0 -1.525011  0.778190 -1.010391
1  0.619824  0.790439 -0.692568
2  1.272323  1.620728  0.192169
3  0.193523  0.070921  1.067544
4  0.057110 -1.007442  1.706704
In [30]:

for index,row in df.iterrows():
    df.loc[index,'d'] = np.random.randint(0, 10)
df
Out[30]:
          a         b         c  d
0 -1.525011  0.778190 -1.010391  9
1  0.619824  0.790439 -0.692568  9
2  1.272323  1.620728  0.192169  1
3  0.193523  0.070921  1.067544  0
4  0.057110 -1.007442  1.706704  9

您可以修改现有的行:

In [31]:
# reset the df by slicing
df = df[list('abc')]
for index,row in df.iterrows():
    row['b'] = np.random.randint(0, 10)
df
Out[31]:
          a  b         c
0 -1.525011  8 -1.010391
1  0.619824  2 -0.692568
2  1.272323  8  0.192169
3  0.193523  2  1.067544
4  0.057110  3  1.706704

但是使用 row 添加新列是行不通的:

In [35]:

df = df[list('abc')]
for index,row in df.iterrows():
    row['d'] = np.random.randint(0,10)
df
Out[35]:
          a  b         c
0 -1.525011  8 -1.010391
1  0.619824  2 -0.692568
2  1.272323  8  0.192169
3  0.193523  2  1.067544
4  0.057110  3  1.706704

4
row[col_head] = 1 ..

请尝试以下命令行:
df.at[index,col_head]=1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接