JTable - различный ComboBox для каждой ячейки в столбце

Я думаю, что лучше использовать Series.value_counts с фильтрацией:

s = got['Name'].value_counts()
got['Name'] = np.where(got['Name'].isin(s.index[s >= 2000]), got['Name'], 'Other')

Или:

got['Name'] = np.where(got['Name'].isin(s.index[s < 2000]), 'Other', got['Name'])

Образец:

df = pd.DataFrame({'Name': ['John', 'Daenerys', 'Cersei', 'Hound', 'Joffrey', 'LittleF'], 
                   'Count': [90000, 50000, 45000, 2000, 1500, 1200]})
got = pd.DataFrame({'Name':np.repeat(df['Name'].values, df['Count'])})

#check sizes
print (got.groupby('Name').size().sort_values(ascending=False))
Name
John        90000
Daenerys    50000
Cersei      45000
Hound        2000
Joffrey      1500
LittleF      1200
dtype: int64

s = got['Name'].value_counts()
got['Name'] = np.where(got['Name'].isin(s.index[s >= 2000]), got['Name'], 'Other')

#check sizes
print (got.groupby('Name').size().sort_values(ascending=False))
Name
John        90000
Daenerys    50000
Cersei      45000
Other        2700
Hound        2000
dtype: int64

1
задан Mihael Keehl 19 January 2019 в 15:50
поделиться

1 ответ

Основной частью этого примера программы является использование собственного редактора ячеек EpisodeEditor. Он динамически определяет «эпизоды» на основе «серий», выбранных в первом столбце.

(Я использовал фиктивный источник данных для этой демонстрации.)

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.util.*;

public class ComboBoxTable
{
  public static void main(String[] args)
  {
    // Mock data source
    DataSource dataSource = new DataSource();

    JComboBox<String> seriesComboBox = new JComboBox<>();
    for (String s : dataSource.getSeries())
    {
      seriesComboBox.addItem(s);
    }

    JTable table = new JTable(
        new String[][] {{"", ""}, {"", ""}, {"", ""}},
        new String[] {"Series", "Episode"});
    table.getColumn("Series").setCellEditor(new DefaultCellEditor(seriesComboBox));
    table.getColumn("Episode").setCellEditor(new EpisodeEditor(dataSource));

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(table));
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

class EpisodeEditor extends AbstractCellEditor implements TableCellEditor
{
  private DataSource dataSource;
  private JComboBox<String> episodesComboBox = new JComboBox<>();

  EpisodeEditor(DataSource dataSource)
  {
    this.dataSource = dataSource;
  }

  @Override
  public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                                                        int row, int column)
  {
    String series = (String) table.getModel().getValueAt(row, 0);

    List<String> episodes = dataSource.getEpisodes(series);
    episodesComboBox.removeAllItems();
    for (String ep : episodes)
    {
      episodesComboBox.addItem(ep);
    }
    episodesComboBox.setSelectedItem(value);
    return episodesComboBox;
  }

  @Override
  public Object getCellEditorValue()
  {
    return episodesComboBox.getSelectedItem();
  }
}

class DataSource
{
  List<String> getSeries()
  {
    return Arrays.asList("Prison Break", "Breaking Bad", "Pokemon");
  }

  List<String> getEpisodes(String series)
  {
    switch (series)
    {
      case "Prison Break":
        return Arrays.asList("Break 1", "Break 2", "Break 3");
      case "Breaking Bad":
        return Arrays.asList("Bad 1", "Bad 2", "Bad 3");
      case "Pokemon":
        return Arrays.asList("P1", "P2", "P3");
      default:
        throw new IllegalArgumentException("Invalid series: " + series);
    }
  }
}
0
ответ дан Prasad Karunagoda 19 January 2019 в 15:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: