【发布时间】:2021-07-12 10:25:22
【问题描述】:
与How to add an empty column to a dataframe? 和Adding a new column to a df each cycle of a for loop 这些问题类似,我想在一列中添加新标签,最初初始化为 null,每个循环的 for 循环。
我有一个 10 行的初始数据集。在 for 循环中,在每个循环中,我都会添加更多行。我想为新行分配一个标签 0,以将它们与数据集中已有的原始行区分开来 (1)。
例如:
df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame
>>> df
a b
0 1 5
1 2 6
2 3 7
在开始 for 循环之前,我正在创建一个新列,将其值初始化为 1:
a b Label
0 1 5 1
1 2 6 1
2 3 7 1
第一次运行后,循环将新行添加到 df。如何将 Label=0 分配给这些行? 预期输出:
a b Label
0 1 5 1
1 2 6 1
2 3 7 1
3 4 8 0
4 5 9 0
...
我尝试如下:
df['Label']=1
labels=df['Label']
for x in difference: # I will need to assign a label 0 to rows not initially included in my original df. Since 5,6 and 7 are not in a, the first run is for x in (5,6,7). I will need to skip this first run otherwise I will assign 0 to my first three rows - that I had initialised to 1
# omitted steps
labels=0
df = pd.DataFrame({"a": a_list, "b": b_list, "Labels": labels})
如前所述,difference 包含 b 中未包含在 a 中的所有值。
而不是预期的输出,我得到以下内容:
a b Label
0 1 5 0
1 2 6 0
2 3 7 0
3 4 8 0
4 5 9 0
...
问题是,目前labels = 0 的值也分配给了我的第一个原始行,因为循环也在为这些行运行,所以最初分配的值 1 被替换。
我认为一种方法可以是查看初始数据帧的长度(分配Label=1)并分配给大于该值0的行。在开头定义thrershold=len(df),然后在创建df之前使用新值,为小于阈值的行分配一个值1,否则为0。但我不知道如何处理行数来尝试这种方法。我认为 .loc 可以解决问题,但我不知道如何编写条件(可能低于初始长度的行,在for 循环之前定义)。
我在想这样的事情:
- 对于初始阈值内的那些行(即,我的 df 的 len),然后分配 1;
- 否则为 0。
这应该在我的代码中定义df 之后设置,以便创建一个考虑值的位置(行索引)的列。
我试过:df.iloc[0:int(len(df)), "Label"]=1,但它给了我一个错误:IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
【问题讨论】:
-
你如何添加新行?你能把代码贴出来吗
-
不幸的是,我无法为此发布整个代码。但也可以考虑添加随机生成的值:
np.random.randint(0,10),如果 b 中的值不在 a 中。 -
我认为另一种方法可能是查看初始数据帧的长度(分配 Label=1)并分配给大于 value=0 的行。在开始,并且在使用新值创建 df 之前,为小于阈值的行分配一个值 1,否则为 0。但我不知道如何处理行数来尝试这种方法
标签: python pandas for-loop indexing