【发布时间】:2023-03-02 23:07:01
【问题描述】:
我有一个 5x500k 的 pandas 数据框,并且想要定位异常索引,其中的内容是异常长的字符串。
for col in df.columns:
print(df[col].apply(str).map(len).max()) #finds max length of a string in the column col
print(df[col].apply(str).map(len)) #Gives length of all strings in the column col
我想做的是在每列中找到最长的字符串,如果没有其他长度相同的字符串(例如,不是多个最长的字符串),则将其设置为 NaN。并保存该值的索引。我想对每一列重复这个,直到没有一列有任何“唯一长”的字符串。
Example input:
a b c d e
0 NaN 54674054 6613722414 2330536 NaN
1 NaN 1234 asdf 2339933 NaN
2 14242 423124 gsdgsgdfgaadfg sdaasda NaN NaN
3 342543 214124 NaN 1231 978ad6f7d8yv 6767969
4 4123 512353 SDFAGdssd 12 87612378y8q7ssdy
5 4473 32325 as asfsda NaN NaN
Should Output:
a b c d e
0 NaN NaN 6613722414 2330536 NaN
1 NaN 1234 asdf 2339933 NaN
2 NaN 423124 NaN NaN NaN
3 NaN 214124 NaN 1231 NaN
4 4123 512353 2SDFAGdssd 12 NaN
5 4473 32325 as asfsda NaN NaN
因为我想从长字符串明显异常中清除我的大数据集。用pandas能轻松做这样的操作吗?
也许问题的更通用版本是,如何找到 pandas 数据框列中所有最长字符串的索引和值?而不仅仅是最长字符串的第一次出现。
非常感谢,
卡尔
【问题讨论】: