假设我创建了一个简单的数据框,并添加了一些列
import pandas as pd
data = {
'price': [6, 5.5, 5, 4.8],
'amount': [10, 12, 8, 6]
}
df = pd.DataFrame(data=data)
df['total'] = df.price * df.amount
df['running_total'] = df.total.cumsum().round(2)
我的数据框现在看起来像这样:
amount price total running_total
0 10 6.0 60.0 60.0
1 12 5.5 66.0 126.0
2 8 5.0 40.0 166.0
3 6 4.8 28.8 194.8
我希望数据框中的行的总计不到160:
row_under_160 = df[df['running_total'] < 160].max()
这一行(系列)如下所示:
amount 12.0
price 6.0
total 66.0
running_total 126.0
dtype: float64
所有价值观看起来都不错,除了价格。出于某种原因,它返回最高价格(6.0),它应该返回5.5,这是相应的值。
我错过了什么/完全错了吗?
答案 0 :(得分:2)
它工作得非常好,但max
值来自已过滤的DataFrame
:
row_under_160 = df[df['running_total'] < 160]
print (row_under_160)
amount price total running_total
0 10 6.0 60.0 60.0
1 12 5.5 66.0 126.0
获取每列的最大值:
print (row_under_160.max())
amount 12.0
price 6.0
total 66.0
running_total 126.0
dtype: float64
但似乎需要过滤的DataFrame的索引running_total
max
loc
print (row_under_160['running_total'].idxmax())
1
print (row_under_160.loc[row_under_160['running_total'].idxmax()])
amount 12.0
price 5.5
total 66.0
running_total 126.0
Name: 1, dtype: float64
并由DataFrame
选择:
[]
如果需要一行print (row_under_160.loc[[row_under_160['running_total'].idxmax()]])
amount price total running_total
1 12 5.5 66.0 126.0
添加max
:
print (row_under_160[row_under_160['running_total'] == row_under_160['running_total'].max()])
amount price total running_total
1 12 5.5 66.0 126.0
或按public class BuyOrders extends Fragment {
private Boolean isConnected = true;
private Socket mSocket;
LinearLayoutManager mLinearLayoutManager;
private RecyclerView mRecyclerView;
private ArrayList<BuyOrderHistory> mMessages = new ArrayList<BuyOrderHistory>();
private RecyclerView.Adapter mAdapter;
private static final String TAG = "BuyOrderHistoryFragment";
public BuyOrders() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new BuyOrderHistoryAdapter(mMessages, context);
if (context instanceof Activity) {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
AppController app = (AppController) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.connect();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("connection_successfull", onConnect);
mSocket.on("buy_orders_data", onBuyOrdersData);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragments_buyorders, container, false);
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("connection_successfull", onConnect);
mSocket.off("buy_orders_data", onBuyOrdersData);
mSocket.disconnect();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_buyorder);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isConnected) {
JSONObject data = (JSONObject)args[0];
Log.d(TAG, String.valueOf(data));
mSocket.emit("fetch_buy_orders",sendFetchBuyOrderRequest(""));
Log.i(TAG, "connected");
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
protected String sendFetchBuyOrderRequest(String s) {
String pageno = "1";
String recordperpage = "10";
String userid = "22";
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("page_no:", pageno );
jsonObject.put("records_per_page", recordperpage);
jsonObject.put("user_id:", userid);
return jsonObject.toString();
}catch (Exception e){
e.printStackTrace();
}
return s;
}
private Emitter.Listener onBuyOrdersData = new Emitter.Listener() {
@Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.v("Data Coming From Server", String.valueOf(data));
String volume;
String bid;
String total;
try {
volume = data.getString("volume");
bid = data.getString("bid");
total = data.getString("total");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addData(volume,bid,total);
}
});
}
};
protected void addData(String volume, String bid, String total){
mMessages.add(new BuyOrderHistory.Builder(BuyOrderHistory.RECEIVER)
.volume(volume).bid(bid).total(total).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void scrollToBottom() {
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
}
protected Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "disconnected");
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH_LONG).show();
}
});
}
};
protected Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e(TAG, "Error connecting");
Toast.makeText(getActivity().getApplicationContext(),
R.string.error_connect, Toast.LENGTH_LONG).show();
}
});
}
};
}
值进行比较:
public class BuyOrderHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
ArrayList<BuyOrderHistory> arrayList;
Context context;
private int RECEIVER = BuyOrderHistory.RECEIVER;
public BuyOrderHistoryAdapter(ArrayList<BuyOrderHistory> arrayList,Context context){
this.arrayList = arrayList;
this.context = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = null;
RecyclerView.ViewHolder vh = null;
if (viewType == RECEIVER){
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_buyorders, parent,false);
vh = new ReceivedDataHolder(v);
}
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == RECEIVER){
((ReceivedDataHolder)holder).volume.setText(arrayList.get(position).getmVolume());
((ReceivedDataHolder)holder).bid.setText(arrayList.get(position).getmBid());
((ReceivedDataHolder)holder).total.setText(arrayList.get(position).getmTotal());
}
}
@Override
public int getItemCount() {
return arrayList == null ? 0 : arrayList.size();
}
@Override
public int getItemViewType(int position) {
if(arrayList.get(position).getmType() == RECEIVER){
}
return RECEIVER;
}
private class ReceivedDataHolder extends RecyclerView.ViewHolder{
public TextView volume, bid, total;
public ReceivedDataHolder(View itemView) {
super(itemView);
volume = (TextView) itemView.findViewById(R.id.tv_buyvolume);
bid = (TextView) itemView.findViewById(R.id.tv_buybid);
total = (TextView) itemView.findViewById(R.id.tv_buytotal);
}
}