How to iterate over pandas dataframe and create new column(如何迭代 pandas 数据框并创建新列)
问题描述
我有一个有 2 列的 pandas 数据框.我想遍历它的行并基于第 2 列中的字符串我想在新创建的第 3 列中添加一个字符串.我试过了:
I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:
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 列中只有变量 2.
But the resulting dataframe has in column 3 only Variable2.
有什么想法我还能做到这一点吗?
Any ideas how else I could do this?
推荐答案
我认为你可以使用 double numpy.where
,什么比循环更快:
I think you can use double numpy.where
, what is faster as loop:
df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4))
如果两个条件都为False
,则需要添加变量:
And if need add variable if both conditions are False
:
df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4, variable5))
示例:
df = pd.DataFrame({'Column2':[1,2,4,3]})
print (df)
Column2
0 1
1 2
2 4
3 3
variable1 = 1
variable2 = 2
variable3 = 3
variable4 = 4
variable5 = 5
df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4, variable5))
print (df)
Column2 Column3
0 1 2
1 2 5
2 4 5
3 3 4
另一个解决方案,谢谢<代码>乔恩克莱门茨:
Another solution, thanks Jon Clements
:
df['Column4'] = df.Column2.map({variable1: variable2, variable3:variable4}).fillna(variable5)
print (df)
Column2 Column3 Column4
0 1 2 2.0
1 2 5 5.0
2 4 5 5.0
3 3 4 4.0
这篇关于如何迭代 pandas 数据框并创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何迭代 pandas 数据框并创建新列


基础教程推荐
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01