信不信由你,在分析我当前的代码之后,numpy数组reversion的重复操作占用了运行时间的一大块.我现在拥有的是基于视图的常见方法:
reversed_arr = arr[::-1]
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以更有效地做到这一点,还是仅仅因为我对不切实际的numpy表现的痴迷而产生的错觉?
我正在尝试在abs(C)上对这个数据框进行排序
A B C
0 10.3 11.3 -0.72
1 16.2 10.9 -0.84
2 18.1 15.2 0.64
3 12.2 11.3 0.31
4 17.2 12.2 -0.75
5 11.6 15.4 -0.08
6 16.0 10.4 0.05
7 18.8 14.7 -0.61
8 12.6 16.3 0.85
9 11.6 10.8 0.93
Run Code Online (Sandbox Code Playgroud)
为此,我必须附加一个新列 D = abs(C),然后对 D 进行排序
df['D']= abs (df['C'])
df.sort_values(by=['D'])
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以用一种方法完成这项工作?
我有一个简单的值列表,我需要其中的索引按原始值顺序(最大到最小)排序。
我们假设列表是
maxList = [7, 3, 6, 9, 1, 3]
Run Code Online (Sandbox Code Playgroud)
结果应该是:
indexedMaxList = [3, 0, 2, 1, 5, 4]
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试过的:
def ClusteringOrder(maxList):
sortedMaxList = maxList.copy()
sortedMaxList.sort(reverse=True)
indexedMaxList = []
for i in range(len(maxList)):
indexedMaxList.append(maxList.index(sortedMaxList[i]))
return(indexedmaxList)
Run Code Online (Sandbox Code Playgroud)
问题很明显,这样做会返回第一次出现重复值的索引。在这种情况下,双 3 将返回 1 两次,因此结果将是:
indexedMaxList = [3, 0, 2, 1, 1, 4]
Run Code Online (Sandbox Code Playgroud)
有没有什么简单的方法可以恢复实际位置?
我有一个Python熊猫数据框,在其中一个名为列status含有三种可能的值:ok,must read x more books,does not read any books yet,在x高于一个整数0.
我想status根据上面的顺序对值进行排序.
例:
name status
0 Paul ok
1 Jean must read 1 more books
2 Robert must read 2 more books
3 John does not read any book yet
Run Code Online (Sandbox Code Playgroud)
我发现了一些有趣的提示,使用Pandas Categorical和map但我不知道如何处理修改字符串的变量值.
我怎样才能做到这一点?
我正在尝试创建一个使用df.iterrows()和的函数Series.nlargest.我想遍历每一行并找到最大的数字,然后将其标记为a 1.这是数据框:
A B C
9 6 5
3 7 2
Run Code Online (Sandbox Code Playgroud)
这是我希望的输出:
A B C
1 0 0
0 1 0
Run Code Online (Sandbox Code Playgroud)
这是我想在这里使用的功能:
def get_top_n(df, top_n):
"""
Parameters
----------
df : DataFrame
top_n : int
The top number to get
Returns
-------
top_numbers : DataFrame
Returns the top number marked with a 1
"""
# Implement Function
for row in df.iterrows():
top_numbers = row.nlargest(top_n).sum()
return top_numbers
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:AttributeError:'tuple'对象没有属性'nlargest'
如何以更整洁的方式重新编写我的功能并实际工作,将不胜感激!提前致谢
我有一个这样的数据框,如何排序。
df = pd.DataFrame({'Date':['Oct20','Nov19','Jan19','Sep20','Dec20']})
Date
0 Oct20
1 Nov19
2 Jan19
3 Sep20
4 Dec20
Run Code Online (Sandbox Code Playgroud)
我熟悉日期排序列表(字符串)
a.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?我应该拆分吗?
我有一个使用plotly 构建堆积条形图的代码示例:
import plotly.graph_objects as go
x = ['2018-01', '2018-02', '2018-03']
fig = go.Figure(go.Bar(x=x, y=[10, 15, 3], name='Client 1'))
fig.add_trace(go.Bar(x=x, y=[12, 7, 14], name='Client 2'))
fig.update_layout(
barmode='stack',
yaxis={'title': 'amount'},
xaxis={
'type': 'category',
'title': 'month',
},
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
输出以下图:
有没有办法调整绘图布局以按值对每个条形的 Y 轴进行排序?
例如,在第二条 (2018-02) 中,客户端 1 的 Y 值较高,蓝色条应位于红色条的顶部。