[英]How can I assign a value to a different column for each row in a dataframe?
I have a dataframe dat
that looks like this: 我有一个看起来像这样的数据帧
dat
:
p1 p2 type replace
1 0 1 1 1
2 1 0 1 1
3 0 0 2 1
...
I want do something like dat['p + str(type)'] = replace
to get: 我想做类似
dat['p + str(type)'] = replace
操作:
p1 p2 type replace
1 1 1 1 1
2 1 0 1 1
3 0 1 2 1
...
How can I do this? 我怎样才能做到这一点? Of course I can't assign in a loop using something like iterrows...
当然我不能使用类似iterrows的循环分配...
Maybe there is some one liner to do this, but if performance is not really an issue, you can easily do this with a simple for loop: 也许有一些衬板可以做到这一点,但是如果性能并不是真正的问题,则可以使用简单的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
If you have much more rows than columns, this will be much faster and is actually easier (and if necessary you can loop over 1, 2, ..): 如果行多于列,这将更快并且实际上更容易(并且如有必要,可以循环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
Just for completeness, I ended up doing the following, which may or may not be the same as what Dan Allan suggested: 为了完整起见,我最终做了以下操作,该操作可能与Dan Allan所建议的相同或不同:
for i in range(2):
df.loc[df['type'] == i + 1, 'p' + str(i + 1)] = df.loc[df['type'] == i + 1, 'replace']
I have a much larger problem than the example I gave (with something like 30 types and thousands of rows in the dataframe), and this solution seems very fast. 我有一个比我给出的示例更大的问题(在数据框中有30种类型和数千行),这种解决方案似乎非常快。 Thanks to all for your help in thinking about this problem!
感谢大家在思考这个问题上的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.