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 数据框并创建新列
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01