从词典系列中提取系列

时间:2016-10-31 14:40:45

标签: python performance pandas dictionary series

我有一个Pandas Series对象,其日期索引和dict值如下:

timeSeries = pd.Series({'2014-05-01': {'property1': 1, 'property2': 2},
                        '2014-05-02': {'property1': 3, 'property2': 4}})

我知道每个dict包含相同的键(property1property2)。有没有办法让系列没有循环只有property1作为值。

即。我想要:

 propertySeries = pd.Series({'2014-05-01': 1,
                             '2014-05-02': 3})

2 个答案:

答案 0 :(得分:2)

您可以valuesSeries转换为numpy array,然后使用DataFrame构造函数:

print (timeSeries.values.tolist())
[{'property1': 1, 'property2': 2}, {'property1': 3, 'property2': 4}]

df = pd.DataFrame(timeSeries.values.tolist(), index=timeSeries.index)
print (df)
            property1  property2
2014-05-01          1          2
2014-05-02          3          4

print (df['property1'])
2014-05-01    1
2014-05-02    3
Name: property1, dtype: int64

print (df['property2'])
2014-05-01    2
2014-05-02    4
Name: property2, dtype: int64

另一个更慢的解决方案:

print (timeSeries.apply(lambda x: x['property1'])) 
2014-05-01    1
2014-05-02    3
dtype: int64

print (timeSeries.apply(lambda x: x['property2'])) 
2014-05-01    2
2014-05-02    4
dtype: int64

如果您自己创建了时间序列,请使用DataFrame.from_dict

timeSeries = pd.DataFrame.from_dict({'2014-05-01': {'property1': 1, 'property2': 2},
                                     '2014-05-02': {'property1': 3, 'property2': 4}}, 
                                      orient='index')


print (timeSeries) 
            property1  property2
2014-05-01          1          2
2014-05-02          3          4

答案 1 :(得分:1)

如果您自己创建了时间序列,则可以改为创建一个DataFrame:

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, PostFragment.OnPostSelectedListener, PostDialogFragment.OnPostSelectedListener, UploadMethodDialogFragment.OnImageSelectedListener {

    private AlertDialog userDialog;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);


        FeedsPagerAdapter adapter = new FeedsPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(PostFragment.newInstance(PostFragment.TYPE_NEW), "NEW");
        adapter.addFragment(PostFragment.newInstance(PostFragment.TYPE_CATEGORY), "CATEGORY");
        adapter.addFragment(PostFragment.newInstance(PostFragment.TYPE_NOTIFICATION), "NOTIFICATIONS");
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header = navigationView.getHeaderView(0);
        TextView navName = (TextView) header.findViewById(R.id.nav_header_name);
        TextView navEmail = (TextView) header.findViewById(R.id.nav_header_email);
        ImageView navProfilePicture = (ImageView) header.findViewById(R.id.nav_profile_picture);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            // Name, email address, and profile photo Url
            String user_name = user.getDisplayName();
            String user_email = user.getEmail();
            Uri pictureURL = user.getPhotoUrl();

            navName.setText("" + user_name);
            navEmail.setText("" + user_email);
            Glide
                    .with(getApplicationContext())
                    .load(pictureURL)
                    .into(navProfilePicture);
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
            viewPager.setCurrentItem(0);

        } else if (id == R.id.nav_gallery) {
            viewPager.setCurrentItem(1);

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    class FeedsPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public FeedsPagerAdapter(android.support.v4.app.FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    @Override
    public void onPostComment(String postKey) {

        if (postKey == null) {
            showAlertDialog("无法连接",
                    "Key : " + postKey, false);
        } else {
            android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
            CommentFragment um = new CommentFragment();

            Bundle args = new Bundle();
            args.putString("postKey", postKey);
            um.setArguments(args);
            um.show(fm, "Comment");
        }

    }

    @Override
    public void onPostLike(final String postKey) {
        final String userKey = FirebaseUtil.getCurrentUserId();
        final DatabaseReference postLikesRef = FirebaseUtil.getLikesRef();
        postLikesRef.child(postKey).child(userKey).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    // User already liked this post, so we toggle like off.
                    postLikesRef.child(postKey).child(userKey).removeValue();
                } else {
                    postLikesRef.child(postKey).child(userKey).setValue(ServerValue.TIMESTAMP);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {

            }
        });
    }

    @Override
    public void onUpdateNotification(final String postKey) {
        final String userKey = FirebaseUtil.getCurrentUserId();
        final DatabaseReference notificationRef = FirebaseUtil.getUserNotificationsRef();
        notificationRef.child(userKey).child(postKey).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("status", false);
                    result.put("count", 0L);
                    notificationRef.child(userKey).child(postKey).updateChildren(result);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {

            }
        });
    }

    @Override
    public void onPostOpenDialog(final String postKey) {
        Bundle bundle = new Bundle();
        bundle.putString("postID", postKey);
        //set Fragment class Arguments
        PostDialogFragment fragObj = new PostDialogFragment();
        fragObj.setArguments(bundle);
        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        fragObj.show(fm, "Post Fragment");
    }

    public void onPicSelected(String filePath) {
        if(filePath!=null){
            Bundle bundle = new Bundle();
            bundle.putString("filePath", filePath);
            //set Fragment class Arguments
            UploadPictureDialogFragment fragObj = new UploadPictureDialogFragment();
            fragObj.setArguments(bundle);
            android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
            fragObj.show(fm, "上载图片");
        }
    }

    public void userDetails(MenuItem item) {

        // [START subscribe_topics]
        FirebaseMessaging.getInstance().subscribeToTopic("6biC3YfNUiWpHqmasa4O74KPWwC2");
        // [END subscribe_topics]

        // Log and toast
        String msg = "Subscribed to news topic";
        Log.d("Subscribe", msg);
        Toast.makeText(HomeActivity.this, msg, Toast.LENGTH_SHORT).show();

    }

    public void upload_method(MenuItem item) {
        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        UploadMethodDialogFragment um = new UploadMethodDialogFragment();
        um.show(fm, "Upload Method");
    }

    private void showAlertDialog(String title, String body, Boolean status) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(title).setMessage(body).setNeutralButton("好的", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    userDialog.dismiss();
                } catch (Exception e) {
                    //
                }
            }
        });
        userDialog = builder.create();
        userDialog.show();
    }

    @Override
    public void onBackPressed() {
        viewPager.setCurrentItem(0);
    }
}