如何在熊猫字符串中对数字进行排序?

时间:2019-05-08 08:06:01

标签: python pandas sorting dataframe

我有一个这样的数据框:

# Have Key Vault create the certificate with a simple policy
$policy = New-AzureKeyVaultCertificatePolicy -SubjectName "CN=mycluster.southcentralus.cloudapp.azure.com" -IssuerName Self -ValidityInMonths 12
Add-AzureKeyVaultCertificate -VaultName noel-temp -Name cert1 -CertificatePolicy $policy

# Download the secret (private key information) associated with the cert
$secret = Get-AzureKeyVaultSecret -VaultName noel-temp -Name cert1
$secretBytes = [System.Convert]::FromBase64String($secret.SecretValueText)
[System.IO.File]::WriteAllBytes("C:\temp\cert1.pfx", $secretBytes)

# Import the certificate to CurrentUser\My
Import-PfxCertificate -FilePath C:\temp\cert1.pfx -CertStoreLocation cert:\CurrentUser\My -Exportable

我想按降序排序

id   String
1    345 -456 -13  879
2    158 -926 -81  249 35 -4 -53  9
3    945 -506 -103

我尝试过:

id String 1 879 345 -13 -457 2 249 158 35 9 -4 -53 -81 -926 3 945 -103 -506

上面的函数进行某种排序,但不是我想要的方式。

1 个答案:

答案 0 :(得分:4)

首先需要将值转换为整数,进行排序,然后再转换回字符串:

f = lambda x: ' '.join(map(str, sorted(map(int, x), reverse=True)))
#another solution
#f = lambda x: ' '.join(str(z) for z in sorted((int(y) for y in x), reverse=True))
df['string'] = df['string'].str.split().map(f)
print (df)
   id                        string
0   1              879 345 -13 -456
1   2  249 158 35 9 -4 -53 -81 -926
2   3                 945 -103 -506

或者:

f = lambda x: ' '.join(map(str, sorted(map(int, x.split()), reverse=True)))
df['string'] = df['string'].map(f)