python - 在 Pandas 系列中对行中的值进行排序的方法?

标签 python pandas vector

考虑以下 pandas.Series 对象:

import pandas as pd

s = pd.Series(["hello there you would like to sort me", "sorted i would like to be", "the yankees played the red sox", "apple apple banana fruit orange cucumber"])

我想对每行的值进行排序,类似于以下方法:

for row in s.index:
    split_words = s.loc[row].split()
    split_words.sort()
    s.loc[row] = " ".join(split_words)

但是,我有一个庞大的数据集,因此矢量化在这里很重要。我如何使用 pandas str 属性来完成同样的事情,但速度要快得多?

最佳答案

我体验过 Python 列表在这些情况下表现更好。应用 piRSquared 的逻辑,列表理解将是:

[' '.join(sorted(sentence.split())) for sentence in s.tolist()]

对于计时,我使用了来自 Peter Norvig's website 的莎士比亚作品.

s = pd.read_table('shakespeare.txt', squeeze=True, header=None)
s = pd.Series(s.tolist()*10)
r1 = s.str.split().apply(sorted).str.join(' ')
r2 = pd.Series([' '.join(sorted(sentence.split())) for sentence in s.tolist()])

r1.equals(r2)
Out: True

%timeit s.str.split().apply(sorted).str.join(' ')
1 loop, best of 3: 2.71 s per loop

%timeit pd.Series([' '.join(sorted(sentence.split())) for sentence in s.tolist()])
1 loop, best of 3: 1.95 s per loop

关于python - 在 Pandas 系列中对行中的值进行排序的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354531/

相关文章:

python - 在循环中从 bigquery 查询数据时出现 Bad Request 错误

python - 如何将数据框列保存为列表? [ Pandas ]

python - 有没有办法就地制作 Series.map,但如果不匹配则保留原始值?

c++ - 有人可以向我解释这一行吗?

c++ - 在 C++ 中使用 vector 传递任意数量的参数

c++ - OSX 10.8 上 C++ 中列表内存泄漏的 vector

python 列表值中的数字格式

python - TCP套接字函数recv()阻塞程序

python - 在所有数据帧列上应用不同 bin 大小的 binning

python - 在 Pandas Dataframe 中进行分组时的多重聚合