在pandas数据框中追加行

时间:2018-05-26 14:40:24

标签: python pandas

我有以下格式的pandas数据框:

      id                                           category
0  17074820                      [15153999, 15213210, 7668302]
1  15153999   [12721363, 9096352, 10788337, 9114021, 10330360]
2  15213210                               [11466240, 12184798]
3   7668302                                          [1539589]
4  12721363  [9465087, 11842208, 11309498, 9465125, 9990074...

我想在行中添加与列表对应的id值,例如:

      id                         category
0  17074820                      15153999
0  17074820                      15213210
0  17074820                      7668302

1 个答案:

答案 0 :(得分:2)

这是通过itertoolsimport pandas as pd, numpy as np from itertools import chain df = pd.DataFrame([[17074820, [15153999, 15213210, 7668302]], [15153999, [12721363, 9096352, 10788337, 9114021, 10330360]]], columns=['id', 'category']) lens = list(map(len, df['category'])) res = pd.DataFrame({'id': np.repeat(df['id'], lens), 'category': list(chain.from_iterable(df['category']))}) print(res) category id 0 15153999 17074820 0 15213210 17074820 0 7668302 17074820 1 12721363 15153999 1 9096352 15153999 1 10788337 15153999 1 9114021 15153999 1 10330360 15153999

的一种解决方案
public void onResume() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        boolean status = prefs.getBoolean("key", true);

        TextView statusView = (TextView) getView().findViewById(R.id.status);


        if (status){
            statusView.setText("Active");
        }else{
            statusView.setText("Disabled");
        }


        super.onResume();
}