假设我有一个带有两列的Pandas DataFrame,例如:
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [100, 200, 300, 400]})
print(df)
a b
0 1 100
1 2 200
2 3 300
3 4 400
假设我还有一个熊猫系列,例如:
s = pd.Series([1, 3, 2, 4])
print(s)
0 1
1 3
2 2
3 4
dtype: int64
如何将a
列排序为与s
序列相同的顺序,并将相应的行值排序在一起?
我想要的输出将是:
a b
0 1 100
1 3 300
2 2 200
3 4 400
有什么办法可以做到这一点?
请在下面查看自我解答。
我经常遇到这些问题,所以我只是想在Pandas中分享我的解决方案。
解决方案1:
使用set_index
该转换a
列索引,然后使用reindex
改变顺序,然后使用rename_axis
更改索引名回a
,然后使用reset_index
该转换a
列从索引回柱:
print(df.set_index('a').reindex(s).rename_axis('a').reset_index('a'))
解决方案2:
使用set_index
该转换a
列索引,然后使用loc
改变顺序,然后使用reset_index
该转换a
列从索引回柱:
print(df.set_index('a').loc[s].reset_index())
解决方案3:
使用iloc
以不同的顺序索引行,然后用map
得到,将适合的顺序df
,使其得到分类与s
系列:
print(df.iloc[list(map(df['a'].tolist().index, s))])
解决方案4:
使用pd.DataFrame
创建一个新的数据框的对象,然后使用sorted
一个key
参数排序依据的数据框s
系列:
print(pd.DataFrame(sorted(df.values.tolist(), key=lambda x: s.tolist().index(x[0])), columns=df.columns))
使用以下代码计时:
import pandas as pd
from timeit import timeit
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [100, 200, 300, 400]})
s = pd.Series([1, 3, 2, 4])
def u10_1():
return df.set_index('a').reindex(s).rename_axis('a').reset_index('a')
def u10_2():
return df.set_index('a').loc[s].reset_index()
def u10_3():
return df.iloc[list(map(df['a'].tolist().index, s))]
def u10_4():
return pd.DataFrame(sorted(df.values.tolist(), key=lambda x: s.tolist().index(x[0])), columns=df.columns)
print('u10_1:', timeit(u10_1, number=1000))
print('u10_2:', timeit(u10_2, number=1000))
print('u10_3:', timeit(u10_3, number=1000))
print('u10_4:', timeit(u10_4, number=1000))
输出:
u10_1: 3.012849470495621
u10_2: 3.072132612502147
u10_3: 0.7498072134665241
u10_4: 0.8109911930595484
@Allen也有一个很好的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句