我有一个包含 2 列的 Pandas 数据框。我想遍历它的行并基于第 2 列中的字符串我想在新创建的第 3 列中添加一个字符串。我试过:
for i in df.index:
if df.ix[i]['Column2']==variable1:
df['Column3'] = variable2
elif df.ix[i]['Column2']==variable3:
df['Column3'] = variable4
print(df)
但是生成的数据框在第 3 列中只有 Variable2。
还有什么办法可以做到这一点吗?
最佳答案
你也可以试试这个(如果你想保留你使用的 for
循环):
new_column = []
for i in df.index:
if df.ix[i]['Column2']==variable1:
new_column.append(variable2)
elif df.ix[i]['Column2']==variable3:
new_column.append(variable4)
else : #if both conditions not verified
new_column.append(other_variable)
df['Column3'] = new_column
关于python - 如何迭代 Pandas 数据框并创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873995/