在python数据框中的逗号分隔字符串中搜索数字

时间:2019-05-27 15:09:27

标签: python python-3.x dataframe

df1:

id, Name, Lastname, Account, ProofID1, ProofID2, transaction_codes_history
1,  ab1,  dc1,      312,     1224,     111,      0, 1.3, 2.1, 3, 4.1, 9.1, 1.1, 7.2
2,  ab2,  dc2,      434,     1225,     112,      0, 1.2, 2.1, 1.4, 3, 4.4, 12.2
3,  ab3,  dc3,      578,     1226,     111,      0, 1.2, 2.1, 1.4, 3, 4.2, 12.1
4,  ab4,  dc4,      624,     1227,     112,      0, 1.1, 7.2
5,  ab5,  dc5,      684,     1228,     113,      0, 1.3, 2.1, 3, 9.2, 11.2

我正在尝试根据其 transaction_codes_history 复制特定列。

如果 transaction_codes_history 至少包含4.17.21.1,那么我们会将这些列复制到数据框中。

transaction_codes_history 是用逗号分隔的浮点数字符串。

预期输出:

Name, Account, ProofID1, ProofID2
ab1,  312,     1224,     111     
ab3,  578,     1225,     111       
ab4,  624,     1227,     112

1 个答案:

答案 0 :(得分:2)

您可以通过创建其他列来实现,例如:

df["to_keep"] = df["transaction_codes_history"].str.contains("1.1|4.1|7.2", regex=True)

然后,您只能保留所需的行:

df[df["to_keep"]][["id", "Name", "Lastname", "Account"]]

我希望它会有所帮助, 尼古拉斯