简体   繁体   中英

Pandas: Reassigning values in dataframe

Suppose I have two columns, ID1 and ID2 amongst many other columns in the dataframe.

ID1      |      ID2      |   etc.
123      |      345
876      |      114
etc.

I need to rearrange the values in ID1 and ID2 in such a way that ID1 always contains the lowest integer value. In this case, row 2 should be switched such that the dataframe looks like this:

ID1      |      ID2
123      |      345
114      |      876

I tried the following, which finds instances where ID2 < ID1 but I don't know how to assign the values in this case.

df.loc[df.ID2 < df.ID1, ['ID1','ID2']] = df.loc[df.ID2 < df.ID1, ['ID2','ID1']]

I need to do this in order to merge this dataframe with another dataframe on ID1 and ID2, where the values might not be aranged in the same way.

Any suggestions?

is that what you want?

In [279]: df
Out[279]:
   ID1  ID2  ID3
0  123  345  100
1  876  114  200
2  111  222  300

In [280]: df[['ID1','ID2']] = df[['ID1','ID2']].apply(np.sort, axis=1)

In [281]: df
Out[281]:
   ID1  ID2  ID3
0  123  345  100
1  114  876  200
2  111  222  300

I guess the faster way would be:

df2 = df.copy()
mask = df.ID1 > df.ID2
df2.ix[mask, 'ID1'] = df.ix[mask, 'ID2']
df2.ix[mask, 'ID2'] = df.ix[mask, 'ID1']

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