简体   繁体   中英

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:

        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:

        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...

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:

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, ..):

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:

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. Thanks to all for your help in thinking about this problem!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM