有条件地将数据合并到现有的熊猫数据框列中

时间:2020-04-24 20:52:03

标签: python pandas merge data-manipulation

我有以下数据:

one_dict = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four"}
two_dict = {0: "light", 1: "calc", 2: "line", 3: "blur", 4: "color"}
np.random.seed(2)
n = 15
a_df = pd.DataFrame(dict(a=np.random.randint(0, 4, n), b=np.random.randint(0, 3, n)))
a_df["c"] = np.nan
a_df = a_df.sort_values("b").reset_index(drop=True)

数据框的外观如下:

In [45]: a_df
Out[45]:
    a  b   c
0   3  0 NaN
1   1  0 NaN
2   0  0 NaN
3   2  0 NaN
4   3  0 NaN
5   1  0 NaN
6   2  1 NaN
7   2  1 NaN
8   3  1 NaN
9   0  2 NaN
10  3  2 NaN
11  3  2 NaN
12  0  2 NaN
13  3  2 NaN
14  1  2 NaN

我想用字典c中的值替换one_dict中的值 和two_dict,结果如下:

In [45]: a_df
Out[45]:
    a  b   c
0   3  0 three
1   1  0 one
2   0  0 zero
3   2  0 .
4   3  0 .
5   1  0 .
6   2  1 calc
7   2  1 calc
8   3  1 blur
9   0  2 NaN
10  3  2 NaN
11  3  2 NaN
12  0  2 NaN
13  3  2 NaN
14  1  2 NaN

尝试

我不确定这是什么好方法。

我认为我可以按照以下方式做一些事情:

merge_df = pd.DataFrame(dict(one = one_dict, two=two_dict)).reset_index()
merge_df['zeros'] = 0
merge_df['ones'] = 1

给予

In [62]: merge_df
Out[62]:
   index    one    two  zeros  ones
0      0   zero  light      0     1
1      1    one   calc      0     1
2      2    two   line      0     1
3      3  three   blur      0     1
4      4   four  color      0     1

然后将其合并到a_df中,但是我不确定如何合并和更新 同时还是这是一个好方法。

编辑

  • 键对应于列a的值
  • .只是速记,应该用其他值填充该值

1 个答案:

答案 0 :(得分:3)

这只是创建具有正确结构并合并的新数据框的问题。

test(
    'should emit [Loading, Error] when getting data fails',
    () async {
      // arrange
      when(mockGetListItems(any))
          .thenAnswer((_) async => Left(ServerFailure()));
      // assert later
      final expected = [
        NoData(),
        Loading(),
        Error(message: ListItemsBloc.serverFailureMessage),
      ];
      expectLater(bloc, emitsInOrder(expected));
      // act
      bloc.add(GetDataListForItems());
    },
  );

  test(
    'should emit [Loading, Error] with a proper message for the error when getting data fails',
    () async {
      // arrange
      when(mockGetListItems(any))
          .thenAnswer((_) async => Left(CacheFailure()));
      // assert later
      final expected = [
        NoData(),
        Loading(),
        Error(message: ListItemsBloc.cacheFailureMessage),
      ];
      expectLater(bloc, emitsInOrder(expected));
      // act
      bloc.add(GetDataListForItems());
    },
  );

输出:

class NoData extends ListItemsState {}

class Loading extends ListItemsState {}

class Loaded extends ListItemsState {
  final ListItemsData itemDataList;
  Loaded({@required this.itemDataList});
  @override
  List<Object> get props => [itemDataList];
}

class Error extends ListItemsState {
  final String message;
  Error({@required this.message});
  @override
  List<Object> get props => [message];
}