Python 有没有一种方法可以在数据帧中循环并基于列表在新列中赋值?
我有一个带有2列的数据帧,我想添加一个新列 此新列应根据我拥有的列表进行更新:Python 有没有一种方法可以在数据帧中循环并基于列表在新列中赋值?,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,我有一个带有2列的数据帧,我想添加一个新列 此新列应根据我拥有的列表进行更新: list = [0,1,2,3,6,7,9,10] 如果col2中的标志为1,则仅使用列表值更新新列。 若标志为0,则不填充新列中的行 当前DF +-------------+---------+ | context | flag | +-------------+---------+ | 0 | 1 | | 0 | 1 | | 0
list = [0,1,2,3,6,7,9,10]
如果col2中的标志为1,则仅使用列表值更新新列。
若标志为0,则不填充新列中的行
当前DF
+-------------+---------+
| context | flag |
+-------------+---------+
| 0 | 1 |
| 0 | 1 |
| 0 | 0 |
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 2 | 0 |
| 4 | 1 |
| 4 | 1 |
| 4 | 0 |
+-------------+---------+
期望测向
+-------------+---------+-------------+
| context | flag | new_context |
+-------------+---------+-------------+
| 0 | 1 | 0 |
| 0 | 1 | 1 |
| 0 | 0 | |
| 2 | 1 | 2 |
| 2 | 1 | 3 |
| 2 | 1 | 6 |
| 2 | 1 | 7 |
| 2 | 0 | |
| 4 | 1 | 9 |
| 4 | 1 | 10 |
| 4 | 0 | |
+-------------+---------+-------------+
现在,我循环遍历列表的索引,并将列表值分配给新的_上下文列。然后我要看一下清单。
这些值填充在正确的位置,但它们都表示为0。我认为它没有正确地遍历列表
list_length = len(list)
i=0
for i in range(list_length])):
df["new_context"] = [list[i] if ele == 0 else "" for ele in df["flag"]]
if df["flag"] == 0: i+=1
我还尝试遍历整个数据帧,但是我认为它只是应用了相同的列表值第一个列表值0
i=0
for index, row in df.iterrows():
df["new_context"] = [list[i] if ele == 0 else "" for ele in df["flag"]]
if row['flag'] == 0: i+=1
如何使用下一个列表值填充标志为1的新列?
似乎i+=1不起作用。让我们试试
l = [0,1,2,3,6,7,9,10]
df['New']=''
df.loc[df.flag==1,'New']=l
df
Out[80]:
context flag New
0 0 1 0
1 0 1 1
2 0 0
3 2 1 2
4 2 1 3
5 2 1 6
6 2 1 7
7 2 0
8 4 1 9
9 4 1 10
10 4 0
让我们试试
l = [0,1,2,3,6,7,9,10]
df['New']=''
df.loc[df.flag==1,'New']=l
df
Out[80]:
context flag New
0 0 1 0
1 0 1 1
2 0 0
3 2 1 2
4 2 1 3
5 2 1 6
6 2 1 7
7 2 0
8 4 1 9
9 4 1 10
10 4 0
非常感谢。工作得很有魅力。我不知道如何在熊猫中使用df.loc。谢谢!工作得很有魅力。我不知道如何在熊猫中使用df.loc。