![](/img/trans.png)
[英]Iterate dataframe and assign value to each row- I get the same value while I want different ones
[英]How can I assign a value to a different column for each row in a dataframe?
我有一个看起来像这样的数据帧dat
:
p1 p2 type replace
1 0 1 1 1
2 1 0 1 1
3 0 0 2 1
...
我想做类似dat['p + str(type)'] = replace
操作:
p1 p2 type replace
1 1 1 1 1
2 1 0 1 1
3 0 1 2 1
...
我怎样才能做到这一点? 当然我不能使用类似iterrows的循环分配...
也许有一些衬板可以做到这一点,但是如果性能并不是真正的问题,则可以使用简单的for循环轻松地做到这一点:
In [134]: df
Out[134]:
p1 p2 type replace
0 0 1 1 1
1 1 0 1 1
2 0 0 2 1
In [135]: for i in df.index:
...: df.loc[i, 'p'+str(df.loc[i, 'type'])] = df.loc[i, 'replace']
In [136]: df
Out[136]:
p1 p2 type replace
0 1 1 1 1
1 1 0 1 1
2 0 1 2 1
如果行多于列,这将更快并且实际上更容易(并且如有必要,可以循环1、2,..):
df["p1"][df["type"]==1] = df["replace"][df["type"]==1]
df["p2"][df["type"]==2] = df["replace"][df["type"]==2]
In [47]: df['p1'].where(~(df['type'] == 1), df['replace'], inplace=True)
In [48]: df['p2'].where(~(df['type'] == 2), df['replace'], inplace=True)
In [49]: df
Out[49]:
p1 p2 type replace
1 1 1 1 1
2 1 0 1 1
3 0 1 2 1
为了完整起见,我最终做了以下操作,该操作可能与Dan Allan所建议的相同或不同:
for i in range(2):
df.loc[df['type'] == i + 1, 'p' + str(i + 1)] = df.loc[df['type'] == i + 1, 'replace']
我有一个比我给出的示例更大的问题(在数据框中有30种类型和数千行),这种解决方案似乎非常快。 感谢大家在思考这个问题上的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.