如何在熊猫中有条件地交换列

时间:2016-09-24 02:47:42

标签: python pandas

我有一个包含4列的pandas数据帧df。例如,这是一个玩具示例:

foo1    foo2     foo3  foo4
egg     cheese   2     1
apple   pear     1     3
french  spanish  10    1

列是foo1,foo2,foo3和foo4

我想交换列foo1和foo2,并且当foo3< foo3和foo4时交换列foo3和foo4。 foo4。结果将是:

foo1     foo2    foo3  foo4
cheese   egg     1     2
apple    pear    1     3
spanish  french  1     10

我可以找到需要与df[df['foo3'] < df['foo4']]交换的行,但是如何有效地进行交换。我的数据框很大。

2 个答案:

答案 0 :(得分:3)

您可以找到void Start() { InitCognito (); } public void InitCognito() { UnityInitializer.AttachToGameObject (this.gameObject); credentials = new CognitoAWSCredentials ( identity_pool_id, // Identity Pool ID region // Region ); Debug.Log ("identity_pool_id = " + identity_pool_id + " region = " + region); credentials.GetIdentityIdAsync(delegate(AmazonCognitoIdentityResult<string> result) { if (result.Exception != null) { Debug.LogError(result.Exception.ToString()); } string identityId = result.Response; Debug.Log("identityId = "+identityId); FBInit(); }); } public void FBInit() { FB.Init(this.OnInitComplete, this.OnHideUnity); Debug.Log( "FB.Init() called with " + FB.AppId); } public void FBLogin() { FB.LogInWithReadPermissions(new List<string>() { "public_profile", "email", "user_friends" }, this.HandleResult); } private void OnInitComplete() { Debug.Log( "Success - Check log for details"); Debug.Log("Success Response: OnInitComplete Called\n"); Debug.Log( string.Format( "OnInitCompleteCalled IsLoggedIn='{0}' IsInitialized='{1}'", FB.IsLoggedIn, FB.IsInitialized)); if (AccessToken.CurrentAccessToken != null) { Debug.Log("Access token = "+AccessToken.CurrentAccessToken.ToString()); } FBLogin (); } private void OnHideUnity(bool isGameShown) { Debug.Log( "Success - Check log for details"); Debug.Log(string.Format("Success Response: OnHideUnity Called {0}\n", isGameShown)); Debug.Log("Is game shown: " + isGameShown); } protected void HandleResult(IResult result) { if (result == null) { Debug.Log("Null Response\n"); return; } // Some platforms return the empty string instead of null. if (!string.IsNullOrEmpty(result.Error)) { Debug.Log( "Error - Check log for details"); Debug.Log( "Error Response:\n" + result.Error); } else if (result.Cancelled) { Debug.Log ("Cancelled - Check log for details"); Debug.Log( "Cancelled Response:\n" + result.RawResult); } else if (!string.IsNullOrEmpty(result.RawResult)) { Debug.Log ("Success - Check log for details"); Debug.Log ("Success Response:\n" + result.RawResult); Debug.Log ("Access Token = "+AccessToken.CurrentAccessToken); Debug.Log ("Access Token = "+AccessToken.CurrentAccessToken.TokenString); Debug.Log ("Access User Id =" + AccessToken.CurrentAccessToken.UserId); credentials.AddLogin ("graph.facebook.com", AccessToken.CurrentAccessToken.TokenString); if (credentials.CurrentLoginProviders.Length > 0) { Debug.Log (credentials.CurrentLoginProviders[0]); } Debug.Log (credentials.GetCachedIdentityId()); } else { Debug.Log ( "Empty Response\n"); } } 行,是的,但是如果您使用布尔系列,则可以轻松实现目标:

df[df['foo3'] < df['foo4']]

注意,您需要RHS末尾的s = df['foo3'] < df['foo4'] df.loc[s, ['foo1','foo2']] = df.loc[s, ['foo2','foo1']].values df.loc[s, ['foo3','foo4']] = df.loc[s, ['foo4','foo3']].values 以防止Pandas对齐列名,这会破坏目的。

答案 1 :(得分:1)

您可以使用pandas.Series.where函数根据条件构建新数据框:

pairs = [('foo1', 'foo2'), ('foo3', 'foo4')]  # construct pairs of columns that need to swapped

df_out = pd.DataFrame() 

# for each pair, swap the values if foo3 < foo4
for l, r in pairs:
    df_out[l] = df[l].where(df.foo3 < df.foo4, df[r])
    df_out[r] = df[r].where(df.foo3 < df.foo4, df[l])

df_out
#     foo1   foo2   foo3  foo4
#0  cheese    egg      1     2
#1   apple   pear      1     3
#2 spanish french      1    10