uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
76adb4644fcd5dcab8712e18 | train | function | @pytest.mark.parametrize("func", ["sum", "any", "shift"])
def test_groupby_column_index_name_lost(func):
# GH: 29764 groupby loses index sometimes
expected = Index(["a"], name="idx")
df = DataFrame([[1]], columns=expected)
df_grouped = df.groupby([1])
result = getattr(df_grouped, func)().columns
... | @pytest.mark.parametrize("func", ["sum", "any", "shift"])
def test_groupby_column_index_name_lost(func):
# GH: 29764 groupby loses index sometimes
| expected = Index(["a"], name="idx")
df = DataFrame([[1]], columns=expected)
df_grouped = df.groupby([1])
result = getattr(df_grouped, func)().columns
tm.assert_index_equal(result, expected)
| 1"
with pytest.raises(ValueError, match=match):
g[["A", "B"]].sum()
@pytest.mark.parametrize("func", ["sum", "any", "shift"])
def test_groupby_column_index_name_lost(func):
# GH: 29764 groupby loses index sometimes
| 64 | 64 | 94 | 39 | 25 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_column_index_name_lost | test_groupby_column_index_name_lost | 2,126 | 2,133 | 2,126 | 2,128 | 1d07650a521d4dd611a93a99e620762d31fb0a2f | bigcode/the-stack | train |
09db8ca1385b99432d77764a | train | function | def test_groupby_level_apply(mframe):
result = mframe.groupby(level=0).count()
assert result.index.name == "first"
result = mframe.groupby(level=1).count()
assert result.index.name == "second"
result = mframe["A"].groupby(level=0).count()
assert result.index.name == "first"
| def test_groupby_level_apply(mframe):
| result = mframe.groupby(level=0).count()
assert result.index.name == "first"
result = mframe.groupby(level=1).count()
assert result.index.name == "second"
result = mframe["A"].groupby(level=0).count()
assert result.index.name == "first"
| if ser.name == ("foo", "one"):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
assert len(agged2.columns) + 1 == len(df.columns)
def test_groupby_level_apply(mframe):
| 64 | 64 | 76 | 9 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_level_apply | test_groupby_level_apply | 913 | 921 | 913 | 914 | 6168210370d7f2a9266e44b195c839e3224e2b84 | bigcode/the-stack | train |
a49326feb2a24b04dccc2cab | train | function | def test_int32_overflow():
B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
A = np.arange(25000)
df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)})
left = df.groupby(["A", "B", "C", "D"]).sum()
right = df.groupby(["D", "C", "B", "A"]).sum()
as... | def test_int32_overflow():
| B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
A = np.arange(25000)
df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)})
left = df.groupby(["A", "B", "C", "D"]).sum()
right = df.groupby(["D", "C", "B", "A"]).sum()
assert len(left) == len(right... | d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
tm.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow():
| 64 | 64 | 123 | 7 | 57 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_int32_overflow | test_int32_overflow | 1,340 | 1,347 | 1,340 | 1,340 | 242b4d2c3ceaeca5d4c3fb748707610fe101edd5 | bigcode/the-stack | train |
e08d7ef856642db67e1b4da3 | train | function | def test_handle_dict_return_value(df):
def f(group):
return {"max": group.max(), "min": group.min()}
def g(group):
return Series({"max": group.max(), "min": group.min()})
result = df.groupby("A")["C"].apply(f)
expected = df.groupby("A")["C"].apply(g)
assert isinstance(result, Seri... | def test_handle_dict_return_value(df):
| def f(group):
return {"max": group.max(), "min": group.min()}
def g(group):
return Series({"max": group.max(), "min": group.min()})
result = df.groupby("A")["C"].apply(f)
expected = df.groupby("A")["C"].apply(g)
assert isinstance(result, Series)
tm.assert_series_equal(result, ... | fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
def test_handle_dict_return_value(df):
| 64 | 64 | 93 | 8 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_handle_dict_return_value | test_handle_dict_return_value | 1,441 | 1,452 | 1,441 | 1,441 | 44cdc380f66955e95e7d8571334f51ad7a2cc11c | bigcode/the-stack | train |
86b471fcf8c9ee4d0f361ba6 | train | function | @pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
index = Index(np.arange(10))
values = Series(np.ones(10), index, dtype=dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"]... | @pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
| index = Index(np.arange(10))
values = Series(np.ones(10), index, dtype=dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
index=index,
)
# this SHOULD be an int
grouped = values.groupby(labels)
agged = grouped.agg(len)
exp... | 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
@pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
| 77 | 77 | 257 | 40 | 37 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_with_na_groups | test_with_na_groups | 280 | 308 | 280 | 283 | 481d5103ef95a8bfe9b318e634a605f05f9f73fb | bigcode/the-stack | train |
1552c5229c0e7e2d7918d5c9 | train | function | def test_groupby_series_with_tuple_name():
# GH 37755
ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
ser.index.name = ("b", "b")
result = ser.groupby(level=0).last()
expected = Series([2, 4], index=[1, 2], name=("a", "a"))
expected.index.name = ("b", "b")
tm.assert_series_eq... | def test_groupby_series_with_tuple_name():
# GH 37755
| ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
ser.index.name = ("b", "b")
result = ser.groupby(level=0).last()
expected = Series([2, 4], index=[1, 2], name=("a", "a"))
expected.index.name = ("b", "b")
tm.assert_series_equal(result, expected)
| ([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_tuple_name():
# GH 37755
| 64 | 64 | 118 | 16 | 48 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_series_with_tuple_name | test_groupby_series_with_tuple_name | 2,147 | 2,154 | 2,147 | 2,148 | 5c4a4eaa81a0aabcb22cfb68334c90a76c671664 | bigcode/the-stack | train |
3b168e950db168d66b0bbac7 | train | function | def test_groupby_two_group_keys_all_nan():
# GH #36842: Grouping over two group keys shouldn't raise an error
df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
result = df.groupby(["a", "b"]).indices
assert result == {}
| def test_groupby_two_group_keys_all_nan():
# GH #36842: Grouping over two group keys shouldn't raise an error
| df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
result = df.groupby(["a", "b"]).indices
assert result == {}
| =r"^nan$"):
grouped.get_group(np.nan)
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
def test_groupby_two_group_keys_all_nan():
# GH #36842: Grouping over two group keys shouldn't raise an error
| 64 | 64 | 81 | 28 | 36 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_two_group_keys_all_nan | test_groupby_two_group_keys_all_nan | 1,321 | 1,325 | 1,321 | 1,322 | 9d214e9620842b5aed3943dcc4c8fd4428676547 | bigcode/the-stack | train |
3cbd3e85cf258009e5b34a60 | train | function | def test_groupby_as_index_select_column_sum_empty_df():
# GH 35246
df = DataFrame(columns=["A", "B", "C"])
left = df.groupby(by="A", as_index=False)["B"].sum()
assert type(left) is DataFrame
assert left.to_dict() == {"A": {}, "B": {}}
| def test_groupby_as_index_select_column_sum_empty_df():
# GH 35246
| df = DataFrame(columns=["A", "B", "C"])
left = df.groupby(by="A", as_index=False)["B"].sum()
assert type(left) is DataFrame
assert left.to_dict() == {"A": {}, "B": {}}
| 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)])
)
tm.assert_series_equal(result, expected)
def test_groupby_as_index_select_column_sum_empty_df():
# GH 35246
| 64 | 64 | 76 | 19 | 45 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_as_index_select_column_sum_empty_df | test_groupby_as_index_select_column_sum_empty_df | 621 | 626 | 621 | 622 | 4d4d032696665ab532395d2b4f24424f1f469708 | bigcode/the-stack | train |
d9455970f442bf4d64988fb8 | train | function | def test_repr():
# GH18203
result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
| def test_repr():
# GH18203
| result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
| Frame,
Grouper,
Index,
MultiIndex,
Series,
Timestamp,
date_range,
read_csv,
to_datetime,
)
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
def test_repr():
# GH18203
| 64 | 64 | 53 | 10 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_repr | test_repr | 29 | 33 | 29 | 30 | 3f61322efe042724c87ee19022e14d0319d5f112 | bigcode/the-stack | train |
47e26a2878069c41e02b328c | train | function | def test_groupby_sort_multiindex_series():
# series multiindex groupby sort argument was not being passed through
# _compress_group_index
# GH 9444
index = MultiIndex(
levels=[[1, 2], [1, 2]],
codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=["a", "b"],
)
mseries = S... | def test_groupby_sort_multiindex_series():
# series multiindex groupby sort argument was not being passed through
# _compress_group_index
# GH 9444
| index = MultiIndex(
levels=[[1, 2], [1, 2]],
codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=["a", "b"],
)
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(
levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"]
)
mseries... | assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
def test_groupby_sort_multiindex_series():
# series multiindex groupby sort argument was not being passed through
# _compress_group_index
# GH 9444
| 77 | 77 | 258 | 38 | 39 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_sort_multiindex_series | test_groupby_sort_multiindex_series | 1,507 | 1,525 | 1,507 | 1,510 | 0a7197d06e93bc053e35123bfc8db75085e5c70d | bigcode/the-stack | train |
8f1549ab87f1b7538400a736 | train | function | def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
key = mframe.index.codes[0]
grouped = mframe.groupby(key)
result = grouped.sum()
expected = mframe.groupby(key.astype("O")).sum()
tm.assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = df_mixed_floats.co... | def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
| key = mframe.index.codes[0]
grouped = mframe.groupby(key)
result = grouped.sum()
expected = mframe.groupby(key.astype("O")).sum()
tm.assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = df_mixed_floats.copy()
df["value"] = range(len(df))
def max_value(gr... | == 21
# corner cases
msg = "Must produce aggregated value"
# exception raised is type Exception
with pytest.raises(Exception, match=msg):
grouped.aggregate(lambda x: x * 2)
def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
| 64 | 64 | 197 | 17 | 47 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_nonobject_dtype | test_groupby_nonobject_dtype | 85 | 106 | 85 | 85 | bffddd1a44df99788b6c571f2be48fa514861d56 | bigcode/the-stack | train |
94638b102c496eee2f1be8cc | train | function | def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
result = df.groupby([Grouper(... | def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
| mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
result = df.groupby([Grouper(level="alpha"), "beta"])
expected = df.groupby(["alpha", "beta"])
assert result.groups == expected.groups
result = df... | .from_arrays(index_array, names=index_names)
expected = Series([3], index=ei)
tm.assert_series_equal(result, expected)
def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
| 64 | 64 | 171 | 35 | 29 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_groups_in_BaseGrouper | test_groupby_groups_in_BaseGrouper | 1,859 | 1,870 | 1,859 | 1,861 | 20ab351fbc49d23197590ea0b32a220ba848beb9 | bigcode/the-stack | train |
3f63759b9ecb80371689d9ae | train | function | def test_groupby_nat_exclude():
# GH 6992
df = DataFrame(
{
"values": np.random.randn(8),
"dt": [
np.nan,
Timestamp("2013-01-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2... | def test_groupby_nat_exclude():
# GH 6992
| df = DataFrame(
{
"values": np.random.randn(8),
"dt": [
np.nan,
Timestamp("2013-01-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
... | columns=["metric", "values"], index=index)
result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "metric"])
tm.assert_frame_equal(result, expected)
def test_groupby_one_row():
# GH 11741
msg = r"^'Z'$"
df1 = DataFrame(np.random.randn(1, 4), co... | 171 | 171 | 571 | 15 | 156 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_nat_exclude | test_groupby_nat_exclude | 1,258 | 1,318 | 1,258 | 1,259 | 50982b55dc8f7aa563d579b867fb9565bf458cc8 | bigcode/the-stack | train |
cd3c49176235beae3dd06932 | train | function | def test_groupby_as_index_series_scalar(df):
grouped = df.groupby(["A", "B"], as_index=False)
# GH #421
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
| def test_groupby_as_index_series_scalar(df):
| grouped = df.groupby(["A", "B"], as_index=False)
# GH #421
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
| arrays = list(zip(*expected.index.values))
expected.insert(0, "A", arrays[0])
expected.insert(1, "B", arrays[1])
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(df):
| 64 | 64 | 70 | 10 | 54 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_as_index_series_scalar | test_groupby_as_index_series_scalar | 773 | 780 | 773 | 773 | 7abafe0f63c49df0737b738c8524a476b50afc1e | bigcode/the-stack | train |
f04413962ec8587f0e97d9cf | train | function | def test_no_dummy_key_names(df):
# see gh-1291
result = df.groupby(df["A"].values).sum()
assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
| def test_no_dummy_key_names(df):
# see gh-1291
| result = df.groupby(df["A"].values).sum()
assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
| ):
names.append(group.name)
return group.copy()
df.groupby("a", sort=False, group_keys=False).apply(f)
expected_names = [0, 1, 2]
assert names == expected_names
def test_no_dummy_key_names(df):
# see gh-1291
| 64 | 64 | 68 | 16 | 47 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_no_dummy_key_names | test_no_dummy_key_names | 1,498 | 1,504 | 1,498 | 1,499 | 9aa41b5ae834dcd87557c4e8231be1c761aa0694 | bigcode/the-stack | train |
def6d5b962038615e8fd9725 | train | function | def test_groupby_empty_list_raises():
# GH 5289
values = zip(range(10), range(10))
df = DataFrame(values, columns=["apple", "b"])
msg = "Grouper and axis must be same length"
with pytest.raises(ValueError, match=msg):
df.groupby([[]])
| def test_groupby_empty_list_raises():
# GH 5289
| values = zip(range(10), range(10))
df = DataFrame(values, columns=["apple", "b"])
msg = "Grouper and axis must be same length"
with pytest.raises(ValueError, match=msg):
df.groupby([[]])
| 4], index=mi)
result = ser.groupby(level=1).mean()
expected = Series([3.0, 2.5], index=["a", "b"])
tm.assert_series_equal(result, expected)
def test_groupby_empty_list_raises():
# GH 5289
| 64 | 64 | 73 | 16 | 48 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_empty_list_raises | test_groupby_empty_list_raises | 1,834 | 1,840 | 1,834 | 1,835 | 6f74ef56a92fb5c95d4142e9ebb7e4f8a50c8bb5 | bigcode/the-stack | train |
1a645e6b9c55056dc0b820c5 | train | function | def test_multifunc_sum_bug():
# GH #1065
x = DataFrame(np.arange(9).reshape(3, 3))
x["test"] = 0
x["fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
| def test_multifunc_sum_bug():
# GH #1065
| x = DataFrame(np.arange(9).reshape(3, 3))
x["test"] = 0
x["fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
| _nonsense_name(float_frame):
# GH #995
s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
def test_multifunc_sum_bug():
# GH #1065
| 64 | 64 | 100 | 15 | 48 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_multifunc_sum_bug | test_multifunc_sum_bug | 1,430 | 1,438 | 1,430 | 1,431 | b25efcd2cc088200dd587ce609d3dbd4b6ce8fe7 | bigcode/the-stack | train |
ad5fff29cde1afd85d4c2dab | train | function | def test_convert_objects_leave_decimal_alone():
s = Series(range(5))
labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert len(x.values.base) > 0
return Decim... | def test_convert_objects_leave_decimal_alone():
| s = Series(range(5))
labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert len(x.values.base) > 0
return Decimal(str(x.mean()))
grouped = s.groupby(labels... | = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone():
| 64 | 64 | 150 | 9 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_convert_objects_leave_decimal_alone | test_convert_objects_leave_decimal_alone | 1,172 | 1,193 | 1,172 | 1,173 | 1d290e7bc778a76a33a2634f661884f5ec1538ac | bigcode/the-stack | train |
d7924d8931a3c6712c483b38 | train | function | @pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
| @pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
| arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
| .assert_frame_equal(result, expected)
result = df.groupby("A").sum()
tm.assert_frame_equal(result, expected)
# TODO: Ensure warning isn't emitted in the first place
@pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
| 64 | 64 | 86 | 26 | 37 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_cython_grouper_series_bug_noncontig | test_cython_grouper_series_bug_noncontig | 1,147 | 1,155 | 1,147 | 1,148 | 46d0e65909a9a6bb7483f6e8b192c197c95d5418 | bigcode/the-stack | train |
f865b108bc2b018b07d3f57a | train | function | def test_nonsense_func():
df = DataFrame([0])
msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
with pytest.raises(TypeError, match=msg):
df.groupby(lambda x: x + "foo")
| def test_nonsense_func():
| df = DataFrame([0])
msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
with pytest.raises(TypeError, match=msg):
df.groupby(lambda x: x + "foo")
| 5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped["A"].apply(np.mean)
tm.assert_series_equal(agged["A"], agged_A)
assert agged.index.name == "first"
def test_nonsense_func():
| 64 | 64 | 58 | 6 | 58 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_nonsense_func | test_nonsense_func | 888 | 892 | 888 | 888 | 165192f82a2ad1b4b9286f36793f967259def01a | bigcode/the-stack | train |
7026e371b2f3c3964de5fd30 | train | function | def test_groupby_series_indexed_differently():
s1 = Series(
[5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
index=Index(["a", "b", "c", "d", "e", "f", "g"]),
)
s2 = Series(
[1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
)
grouped = s1.groupby(s2)
a... | def test_groupby_series_indexed_differently():
| s1 = Series(
[5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
index=Index(["a", "b", "c", "d", "e", "f", "g"]),
)
s2 = Series(
[1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
)
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.r... | Series((1 + 2j, 5 + 10j))
result = a.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = a.sum(level=0)
tm.assert_series_equal(result, expected)
def test_groupby_series_indexed_differently():
| 64 | 64 | 185 | 11 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_series_indexed_differently | test_groupby_series_indexed_differently | 987 | 999 | 987 | 987 | d97312783b1188e657bd3828ef4f1cdf0de84e12 | bigcode/the-stack | train |
d9fdf95c8eb6005ff8c00a3e | train | function | def test_groupby_dtype_inference_empty():
# GH 6733
df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
assert df["x"].dtype == np.float64
result = df.groupby("x").first()
exp_index = Index([], name="x", dtype=np.float64)
expected = DataFrame({"range": Series([], index=exp_index, dt... | def test_groupby_dtype_inference_empty():
# GH 6733
| df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
assert df["x"].dtype == np.float64
result = df.groupby("x").first()
exp_index = Index([], name="x", dtype=np.float64)
expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")})
tm.assert_frame_equal(result, expecte... | (convert_fast)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
def test_groupby_dtype_inference_empty():
# GH 6733
| 64 | 64 | 110 | 16 | 48 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_dtype_inference_empty | test_groupby_dtype_inference_empty | 1,196 | 1,204 | 1,196 | 1,197 | bdf5da90e88dcc19ceebc0e5329d4046004b08b5 | bigcode/the-stack | train |
cfa34dfe357ef7af7f551b1e | train | function | def test_omit_nuisance(df):
grouped = df.groupby("A")
result = grouped.mean()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
tm.assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
df = df.loc[:, ["A", "C",... | def test_omit_nuisance(df):
| grouped = df.groupby("A")
result = grouped.mean()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
tm.assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
df = df.loc[:, ["A", "C", "D"]]
df["E"] = datetim... | ()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
def test_omit_nuisance(df):
| 66 | 66 | 223 | 9 | 57 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_omit_nuisance | test_omit_nuisance | 823 | 845 | 823 | 823 | c9ccf3cf99481445a35408ba9ccea82f589cd9ad | bigcode/the-stack | train |
2a2f344bd24e4c78627f357a | train | function | def test_groupby_as_index_cython(df):
data = df
# single-key
grouped = data.groupby("A", as_index=False)
result = grouped.mean()
expected = data.groupby(["A"]).mean()
expected.insert(0, "A", expected.index)
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected... | def test_groupby_as_index_cython(df):
| data = df
# single-key
grouped = data.groupby("A", as_index=False)
result = grouped.mean()
expected = data.groupby(["A"]).mean()
expected.insert(0, "A", expected.index)
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
# multi-key
grouped = data.... | ):
# GH15072
grouped = df.groupby("A", as_index=False)
msg = r"Column\(s\) C already selected"
with pytest.raises(IndexError, match=msg):
grouped["C"].__getitem__("D")
def test_groupby_as_index_cython(df):
| 64 | 64 | 171 | 10 | 54 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_as_index_cython | test_groupby_as_index_cython | 750 | 770 | 750 | 750 | 0aa206b3b3995c75ce79f7a85c5afcda7a9f6910 | bigcode/the-stack | train |
718c0847dfcf1b0416085032 | train | function | def test_skip_group_keys():
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_frame_equa... | def test_skip_group_keys():
| tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_frame_equal(result, expected)
grou... | a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
def test_skip_group_keys():
| 64 | 64 | 158 | 6 | 58 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_skip_group_keys | test_skip_group_keys | 1,400 | 1,418 | 1,400 | 1,401 | eb5f4e2cea437325a3e1d0bdd9bf49b650d02a6c | bigcode/the-stack | train |
1340e648c40413fbe55b19b6 | train | function | def test_transform_doesnt_clobber_ints():
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
gb = df.groupby("a")
result = gb.transform("mean")
gb2 = df2.groupby("a")
expected =... | def test_transform_doesnt_clobber_ints():
# GH 7972
| n = 6
x = np.arange(n)
df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
gb = df.groupby("a")
result = gb.transform("mean")
gb2 = df2.groupby("a")
expected = gb2.transform("mean")
tm.assert_frame_equal(result,... | ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
def test_transform_doesnt_clobber_ints():
# GH 7972
| 64 | 64 | 148 | 19 | 45 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_transform_doesnt_clobber_ints | test_transform_doesnt_clobber_ints | 1,656 | 1,668 | 1,656 | 1,657 | 39652b869eb40505eb2ca911d57850a0f05fcd57 | bigcode/the-stack | train |
2305bee3de35b864f1864983 | train | function | def test_groupby_as_index_corner(df, ts):
msg = "as_index=False only valid with DataFrame"
with pytest.raises(TypeError, match=msg):
ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambd... | def test_groupby_as_index_corner(df, ts):
| msg = "as_index=False only valid with DataFrame"
with pytest.raises(TypeError, match=msg):
ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambda x: x.lower(), as_index=False, axis=1)
| ", "B"], as_index=False)
# GH #421
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_corner(df, ts):
| 64 | 64 | 91 | 11 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_as_index_corner | test_groupby_as_index_corner | 783 | 790 | 783 | 783 | 3f970f5d7d5e7cb6e60d57fd3c32bcaa342143c8 | bigcode/the-stack | train |
3c5a3a397f3d74f4de4c7f6f | train | function | def test_groupby_series_with_name(df):
result = df.groupby(df["A"]).mean()
result2 = df.groupby(df["A"], as_index=False).mean()
assert result.index.name == "A"
assert "A" in result2
result = df.groupby([df["A"], df["B"]]).mean()
result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
... | def test_groupby_series_with_name(df):
| result = df.groupby(df["A"]).mean()
result2 = df.groupby(df["A"], as_index=False).mean()
assert result.index.name == "A"
assert "A" in result2
result = df.groupby([df["A"], df["B"]]).mean()
result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
assert result.index.names == ("A", "B... | data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_name(df):
| 64 | 64 | 123 | 9 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_series_with_name | test_groupby_series_with_name | 1,067 | 1,077 | 1,067 | 1,067 | c6c9a1035ec65db3c8e964f25dd77a3c05c3199a | bigcode/the-stack | train |
7c913f7a9d4a711e16cc9ba0 | train | function | def test_groupby_reindex_inside_function():
periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
def agg_before(func, fix=False):
"""
Run an aggregate func on the subset of dat... | def test_groupby_reindex_inside_function():
| periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
def agg_before(func, fix=False):
"""
Run an aggregate func on the subset of data.
"""
def _func(data):
... | .groupby(level=["a", "b"], sort=False).first()
tm.assert_series_equal(result, mseries_result)
result = mseries.groupby(level=["a", "b"], sort=True).first()
tm.assert_series_equal(result, mseries_result.sort_index())
def test_groupby_reindex_inside_function():
| 64 | 64 | 212 | 9 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_reindex_inside_function | test_groupby_reindex_inside_function | 1,528 | 1,553 | 1,528 | 1,529 | 90e204e32c22fdf298a7f6910098b08490787895 | bigcode/the-stack | train |
03d2d15fd6a987772605406b | train | function | def test_groupby_mixed_type_columns():
# GH 13432, unorderable types in py3
df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
result = df.groupby("A").first()
tm.assert_frame_equal(result, expected)
result = df.group... | def test_groupby_mixed_type_columns():
# GH 13432, unorderable types in py3
| df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
result = df.groupby("A").first()
tm.assert_frame_equal(result, expected)
result = df.groupby("A").sum()
tm.assert_frame_equal(result, expected)
| x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
def test_groupby_mixed_type_columns():
# GH 13432, unorderable types in py3
| 64 | 64 | 114 | 24 | 40 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_mixed_type_columns | test_groupby_mixed_type_columns | 1,134 | 1,143 | 1,134 | 1,135 | c8ba72d2cc890677318aed8a650204c88f28720e | bigcode/the-stack | train |
3921f5058d9dec3e14d3fc4e | train | function | def test_multi_key_multiple_functions(df):
grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected)
| def test_multi_key_multiple_functions(df):
| grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected)
| 2"]),
},
index=["one", "two", "three", "four", "five", "six"],
)
# only verify that it works for now
grouped = df.groupby(["k1", "k2"])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(df):
| 64 | 64 | 70 | 8 | 56 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_multi_key_multiple_functions | test_multi_key_multiple_functions | 505 | 510 | 505 | 505 | 2b55d070fe5ca39a60c680345c46cb5d81a9e77b | bigcode/the-stack | train |
1e3e974ac2573810830299f5 | train | function | def test_series_grouper_noncontig_index():
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(m... | def test_series_grouper_noncontig_index():
| index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
| , 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
def test_series_grouper_noncontig_index():
| 64 | 64 | 98 | 11 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_series_grouper_noncontig_index | test_series_grouper_noncontig_index | 1,158 | 1,169 | 1,158 | 1,158 | 43dc8286853f3357ce139baea78170d3fb892bf8 | bigcode/the-stack | train |
704381b0d20738b5664d9782 | train | function | def test_no_nonsense_name(float_frame):
# GH #995
s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
| def test_no_nonsense_name(float_frame):
# GH #995
| s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
| result = grouped.apply(lambda x: x.sort_values()[:3])
pieces = [group.sort_values()[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_series_equal(result, expected)
def test_no_nonsense_name(float_frame):
# GH #995
| 64 | 64 | 52 | 15 | 49 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_no_nonsense_name | test_no_nonsense_name | 1,421 | 1,427 | 1,421 | 1,422 | c9b79b84c81fe22544f341cd32a2baab92d9c83c | bigcode/the-stack | train |
028fa3356a4adba650458516 | train | function | def test_groupby_multiple_key(df):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
agged = grouped.sum()
tm.assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby(
[lambda x: x.year, lambda x: x.month, lambda x: x.day], a... | def test_groupby_multiple_key(df):
| df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
agged = grouped.sum()
tm.assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby(
[lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1
)
agged = grouped.ag... | ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_multiple_key(df):
| 64 | 64 | 161 | 8 | 56 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_multiple_key | test_groupby_multiple_key | 793 | 808 | 793 | 793 | 0ea26679465c6600d08c38a0959b22e945ec0359 | bigcode/the-stack | train |
5fefefc98d8c6442cbfa839e | train | function | def test_groupby_agg_ohlc_non_first():
# GH 21716
df = DataFrame(
[[1], [1]],
columns=["foo"],
index=date_range("2018-01-01", periods=2, freq="D"),
)
expected = DataFrame(
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
columns=MultiIndex.from_tuples(
(
... | def test_groupby_agg_ohlc_non_first():
# GH 21716
| df = DataFrame(
[[1], [1]],
columns=["foo"],
index=date_range("2018-01-01", periods=2, freq="D"),
)
expected = DataFrame(
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
columns=MultiIndex.from_tuples(
(
("foo", "sum", "foo"),
("foo", ... | .from_product([[1, 2], [3, 4]]))
with pytest.raises(KeyError, match=r"^\(7, 8\)$"):
df.groupby((7, 8)).mean()
def test_groupby_agg_ohlc_non_first():
# GH 21716
| 64 | 64 | 216 | 19 | 45 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_agg_ohlc_non_first | test_groupby_agg_ohlc_non_first | 1,791 | 1,815 | 1,791 | 1,792 | f62ce3eca4ead094922c44108ed65c07062e1dea | bigcode/the-stack | train |
b3f64593cc21bcef52532ad2 | train | function | @pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure tha... | @pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure tha... | df = DataFrame(
{
"int_groups": [3, 1, 0, 1, 0, 3, 3, 3],
"string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"],
"ints": [8, 7, 4, 5, 2, 9, 1, 1],
"floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5],
"strings": ["z", "d", "a", "e", "word", "word2... | @pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure tha... | 102 | 99 | 331 | 102 | 0 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_preserves_sort | test_groupby_preserves_sort | 1,671 | 1,700 | 1,671 | 1,681 | 429eacca31e32671a45c72995b6d52cbd38fde39 | bigcode/the-stack | train |
20ad2bf26910c5cb2f5556ab | train | function | @pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
data = df
grouped = data.groupby(["A", "B"])
result1 = op(grouped)
keys = []
values = []
for n1, gp1 in data.groupby("A"):
for n2, gp2 in gp1.groupby("B"):
key... | @pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
| data = df
grouped = data.groupby(["A", "B"])
result1 = op(grouped)
keys = []
values = []
for n1, gp1 in data.groupby("A"):
for n2, gp2 in gp1.groupby("B"):
keys.append((n1, n2))
values.append(op(gp2.loc[:, ["C", "D"]]))
mi = MultiIndex.from_tuples(keys, nam... | )],
keys=["D", "E", "F"],
axis=1,
)
assert isinstance(agged.index, MultiIndex)
assert isinstance(expected.index, MultiIndex)
tm.assert_frame_equal(agged, expected)
@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
| 79 | 79 | 265 | 29 | 50 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_multiple_columns | test_groupby_multiple_columns | 574 | 604 | 574 | 575 | 3747f3afd6917dbaca044c94932502ebc88a8a30 | bigcode/the-stack | train |
c47b9369c2e56915361589b6 | train | function | def test_consistency_name():
# GH 12363
df = DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
"C": np.random.randn(8) + 1.0,
"D": np.arange(8),
}
)
... | def test_consistency_name():
# GH 12363
| df = DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
"C": np.random.randn(8) + 1.0,
"D": np.arange(8),
}
)
expected = df.groupby(["A"]).B.count()
re... | ["C"]
assert result.count().name == "C"
assert result.mean().name == "C"
testFunc = lambda x: np.sum(x) * 2
assert result.agg(testFunc).name == "C"
def test_consistency_name():
# GH 12363
| 64 | 64 | 137 | 13 | 51 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_consistency_name | test_consistency_name | 1,090 | 1,104 | 1,090 | 1,092 | 6a85231aac45c0240a3863edfb98174fb6f0bf06 | bigcode/the-stack | train |
e317f041f77da632583dc6e7 | train | function | def test_groupby_level_nonmulti():
# GH 1313, GH 13901
s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
result = s.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = ... | def test_groupby_level_nonmulti():
# GH 1313, GH 13901
| s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
result = s.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[0]).sum()
tm.assert_series_equal(resul... | ])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]])
expected0 = mframe.groupby(mapped_level0).sum()
expected1 = mframe.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = "first", "second"
tm.assert_frame_equal(result0, expected0)
tm.assert_frame_equ... | 109 | 109 | 364 | 20 | 89 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_level_nonmulti | test_groupby_level_nonmulti | 943 | 972 | 943 | 944 | f066ecffb973fa7d04a11ff6e6e4bde1d659658a | bigcode/the-stack | train |
9a5627839f41bfaf8f21c03b | train | function | def test_len():
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
assert len(grouped) == len(df)
grouped = df.groupby([lambda x: x.year, lambda x: x.month])
expected = len({(x.year, x.month) for x in df.index})
assert len(grouped) == expect... | def test_len():
| df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
assert len(grouped) == len(df)
grouped = df.groupby([lambda x: x.year, lambda x: x.month])
expected = len({(x.year, x.month) for x in df.index})
assert len(grouped) == expected
# issue ... | agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=0.8)
tm.assert_frame_equal(agg_result, expected)
tm.assert_frame_equal(apply_result, expected, check_names=False)
def test_len():
| 64 | 64 | 167 | 4 | 60 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_len | test_len | 253 | 266 | 253 | 253 | e9edf7f8fb0cd2605ba2556a75442ce925376923 | bigcode/the-stack | train |
75ace88a5918ae645638e107 | train | function | def test_groupby_duplicate_columns():
# GH: 31735
df = DataFrame(
{"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
).astype(object)
df.columns = ["A", "B", "B"]
result = df.groupby([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])... | def test_groupby_duplicate_columns():
# GH: 31735
| df = DataFrame(
{"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
).astype(object)
df.columns = ["A", "B", "B"]
result = df.groupby([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])
tm.assert_frame_equal(result, expected)
| "], name="idx")
df = DataFrame([[1]], columns=expected)
df_grouped = df.groupby([1])
result = getattr(df_grouped, func)().columns
tm.assert_index_equal(result, expected)
def test_groupby_duplicate_columns():
# GH: 31735
| 64 | 64 | 138 | 15 | 49 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_duplicate_columns | test_groupby_duplicate_columns | 2,136 | 2,144 | 2,136 | 2,137 | 819093378264f105b52fe0418c0103e0ed64af66 | bigcode/the-stack | train |
e240f2db0e37e5cf88ab2d5d | train | function | @pytest.mark.parametrize(
"idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))]
)
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning")
def test_dup_labels_output_shape(groupby_func, idx):
if groupby_func in {"size", "ngroup", "cumcount"}:
pytest.skip("Not appli... | @pytest.mark.parametrize(
"idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))]
)
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning")
def test_dup_labels_output_shape(groupby_func, idx):
| if groupby_func in {"size", "ngroup", "cumcount"}:
pytest.skip("Not applicable")
df = DataFrame([[1, 1]], columns=idx)
grp_by = df.groupby([0])
args = []
if groupby_func in {"fillna", "nth"}:
args.append(0)
elif groupby_func == "corrwith":
args.append(df)
elif group... | expected)
@pytest.mark.parametrize(
"idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))]
)
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning")
def test_dup_labels_output_shape(groupby_func, idx):
| 64 | 64 | 214 | 62 | 2 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_dup_labels_output_shape | test_dup_labels_output_shape | 1,992 | 2,015 | 1,992 | 1,996 | 6046334c500630300fdab9add3a77d3132dba7de | bigcode/the-stack | train |
9964c5b3d682d548826526ec | train | function | @pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
... | @pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
... | tz = tz_naive_fixture
data = {
"id": ["A", "B", "A", "B", "A", "B"],
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"... | @pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
... | 355 | 161 | 539 | 355 | 0 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_shift_bfill_ffill_tz | test_shift_bfill_ffill_tz | 1,895 | 1,958 | 1,895 | 1,940 | 35572182128857ebd0c5f1ffef2f7170e08f5443 | bigcode/the-stack | train |
f10837ec021f87a9ce265e55 | train | function | def test_empty_groups_corner(mframe):
# handle empty groups
df = DataFrame(
{
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
"k3": ["foo", "bar"] * 3,
"v1": np.random.randn(6),
"v2": np.random.ra... | def test_empty_groups_corner(mframe):
# handle empty groups
| df = DataFrame(
{
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
"k3": ["foo", "bar"] * 3,
"v1": np.random.randn(6),
"v2": np.random.randn(6),
}
)
grouped = df.groupby(["k1", "k2"])
... | _omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"])
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
def test_empty_groups_corner(mframe):
# handle empty groups
| 64 | 64 | 216 | 14 | 50 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_empty_groups_corner | test_empty_groups_corner | 864 | 885 | 864 | 865 | 9d630435a059f4e1b23d3ff09241e3208865c280 | bigcode/the-stack | train |
5d34acbe822ff5d09cad5741 | train | function | def test_multi_func(df):
col1 = df["A"]
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = df.groupby(["A", "B"]).mean()
# TODO groupby get drops names
tm.assert_frame_equal(
agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names... | def test_multi_func(df):
| col1 = df["A"]
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = df.groupby(["A", "B"]).mean()
# TODO groupby get drops names
tm.assert_frame_equal(
agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False
)
# some ... | result = grouped["C"].agg([np.mean, np.std])
assert result.index.name == "A"
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"foo": np.mean, "bar": np.std})
def test_multi_func(df):
| 72 | 72 | 243 | 6 | 66 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_multi_func | test_multi_func | 477 | 502 | 477 | 477 | 6002414df0a745f296322047f0f2b9709e13acc2 | bigcode/the-stack | train |
ece81e0f7f8f23e8490285ca | train | function | def test_groupby_wrong_multi_labels():
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"... | def test_groupby_wrong_multi_labels():
| data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"])
result = grouped.agg(np.mean)
... | ):
grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
) # Note: no names when grouping by value
def test_groupby_wrong_multi_labels():
| 64 | 64 | 158 | 8 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_wrong_multi_labels | test_groupby_wrong_multi_labels | 1,050 | 1,064 | 1,050 | 1,050 | 63f6771dede1016c68f61eefab8845a995ae7754 | bigcode/the-stack | train |
0f79b542edeb494fef59f0e5 | train | function | def test_frame_groupby_columns(tsframe):
mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
grouped = tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == len(tsframe)
assert len(aggregated.columns) == 2
# transform
tf = lambda x: x - x... | def test_frame_groupby_columns(tsframe):
| mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
grouped = tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == len(tsframe)
assert len(aggregated.columns) == 2
# transform
tf = lambda x: x - x.mean()
groupedT = tsframe.T.groupby(... | ].weekday() == weekday
# groups / group_indices
groups = grouped.groups
indices = grouped.indices
for k, v in groups.items():
samething = tsframe.index.take(indices[k])
assert (samething == v).all()
def test_frame_groupby_columns(tsframe):
| 64 | 64 | 152 | 9 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_frame_groupby_columns | test_frame_groupby_columns | 431 | 447 | 431 | 431 | 3ff651e807504861d7986962426cbc3daf93507f | bigcode/the-stack | train |
ce47ca06dad0659a81f4cac9 | train | function | def test_ops_not_as_index(reduction_func):
# GH 10355, 21090
# Using as_index=False should not modify grouped column
if reduction_func in ("corrwith",):
pytest.skip("Test not applicable")
if reduction_func in ("nth", "ngroup"):
pytest.skip("Skip until behavior is determined (GH #5755)"... | def test_ops_not_as_index(reduction_func):
# GH 10355, 21090
# Using as_index=False should not modify grouped column
| if reduction_func in ("corrwith",):
pytest.skip("Test not applicable")
if reduction_func in ("nth", "ngroup"):
pytest.skip("Skip until behavior is determined (GH #5755)")
df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
expected = getattr(df.groupby("a"), redu... | )()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
tm.assert_frame_equal(left, right)
def test_ops_not_as_index(reduction_func):
# GH 10355, 21090
# Using as_index=False should not modify grouped column
| 70 | 70 | 235 | 33 | 37 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_ops_not_as_index | test_ops_not_as_index | 685 | 713 | 685 | 688 | 6397fc796a4cc49c951f588e3e4d55bf2b671452 | bigcode/the-stack | train |
52a00288eb74a1d9f7880587 | train | function | def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
df = DataFrame(
{
"eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(),
"thename": range(0, 20),
}
)
df["year"] = df.set_index("eventDate")... | def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
| df = DataFrame(
{
"eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(),
"thename": range(0, 20),
}
)
df["year"] = df.set_index("eventDate").index.year
df["month"] = df.set_index("eventDate").index.month
with pytest.raises(KeyError, match=... | =sort_column)
g = df.groupby(group_column)
def test_sort(x):
tm.assert_frame_equal(x, x.sort_values(by=sort_column))
g.apply(test_sort)
def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
| 64 | 64 | 143 | 25 | 39 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_pivot_table_values_key_error | test_pivot_table_values_key_error | 1,703 | 1,718 | 1,703 | 1,704 | da3b2d31ef7bb60dc7ff59cbc2c18f55f1a91e84 | bigcode/the-stack | train |
ccf914e4eeeecebc14a015d9 | train | function | def test_groupby_multiindex_missing_pair():
# GH9049
df = DataFrame(
{
"group1": ["a", "a", "a", "b"],
"group2": ["c", "c", "d", "c"],
"value": [1, 1, 1, 5],
}
)
df = df.set_index(["group1", "group2"])
df_grouped = df.groupby(level=["group1", "grou... | def test_groupby_multiindex_missing_pair():
# GH9049
| df = DataFrame(
{
"group1": ["a", "a", "a", "b"],
"group2": ["c", "c", "d", "c"],
"value": [1, 1, 1, 5],
}
)
df = df.set_index(["group1", "group2"])
df_grouped = df.groupby(level=["group1", "group2"], sort=True)
res = df_grouped.agg("sum")
idx... | , x.day))
closure_bad = grouped.agg({"high": agg_before(np.max)})
closure_good = grouped.agg({"high": agg_before(np.max, True)})
tm.assert_frame_equal(closure_bad, closure_good)
def test_groupby_multiindex_missing_pair():
# GH9049
| 64 | 64 | 193 | 15 | 49 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_multiindex_missing_pair | test_groupby_multiindex_missing_pair | 1,556 | 1,574 | 1,556 | 1,557 | ccf8762d5933ca6c4c21793792dc7b6976d53976 | bigcode/the-stack | train |
37bf7e252b468de5f568e56e | train | function | def test_groupby_keys_same_size_as_index():
# GH 11185
freq = "s"
index = date_range(
start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
result = df.groupby([Grouper(level=0, freq=freq), "m... | def test_groupby_keys_same_size_as_index():
# GH 11185
| freq = "s"
index = date_range(
start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "met... | 4], "val": np.random.randn(2)})
result = df.groupby(["foo", "bar"]).mean()
expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]]
def test_groupby_keys_same_size_as_index():
# GH 11185
| 64 | 64 | 132 | 17 | 46 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_keys_same_size_as_index | test_groupby_keys_same_size_as_index | 1,234 | 1,244 | 1,234 | 1,235 | fa5f839b8dae5978f3f5cc0bcb2fd7007928aa08 | bigcode/the-stack | train |
a41d5a771decf37640013243 | train | function | def test_groupby_multiindex_nat():
# GH 9236
values = [
(pd.NaT, "a"),
(datetime(2012, 1, 2), "a"),
(datetime(2012, 1, 2), "b"),
(datetime(2012, 1, 3), "a"),
]
mi = MultiIndex.from_tuples(values, names=["date", None])
ser = Series([3, 2, 2.5, 4], index=mi)
result... | def test_groupby_multiindex_nat():
# GH 9236
| values = [
(pd.NaT, "a"),
(datetime(2012, 1, 2), "a"),
(datetime(2012, 1, 2), "b"),
(datetime(2012, 1, 3), "a"),
]
mi = MultiIndex.from_tuples(values, names=["date", None])
ser = Series([3, 2, 2.5, 4], index=mi)
result = ser.groupby(level=1).mean()
expected = Ser... | =date_range("2018-01-01", periods=2, freq="D"),
)
result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"])
tm.assert_frame_equal(result, expected)
def test_groupby_multiindex_nat():
# GH 9236
| 64 | 64 | 157 | 15 | 49 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_multiindex_nat | test_groupby_multiindex_nat | 1,818 | 1,831 | 1,818 | 1,819 | eefee376d7b2d48b001e5cc482a50e8aeb0daba1 | bigcode/the-stack | train |
c9da6755456f418cf6ab439c | train | function | def test_frame_set_name_single(df):
grouped = df.groupby("A")
result = grouped.mean()
assert result.index.name == "A"
result = df.groupby("A", as_index=False).mean()
assert result.index.name != "A"
result = grouped.agg(np.mean)
assert result.index.name == "A"
result = grouped.agg({"C... | def test_frame_set_name_single(df):
| grouped = df.groupby("A")
result = grouped.mean()
assert result.index.name == "A"
result = df.groupby("A", as_index=False).mean()
assert result.index.name != "A"
result = grouped.agg(np.mean)
assert result.index.name == "A"
result = grouped.agg({"C": np.mean, "D": np.std})
assert... | x.mean()
groupedT = tsframe.T.groupby(mapping, axis=0)
tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
# iterate
for k, v in grouped:
assert len(v.columns) == 2
def test_frame_set_name_single(df):
| 64 | 64 | 204 | 8 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_frame_set_name_single | test_frame_set_name_single | 450 | 474 | 450 | 450 | ad25426c177cb2cb03826803792aa9b8e12a75e9 | bigcode/the-stack | train |
ed0beafbd2d951cc6eea2f84 | train | function | def test_omit_nuisance_sem(df):
# GH 38774 - sem should work with nuisance columns
grouped = df.groupby("A")
result = grouped.sem()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem()
tm.assert_frame_equal(result, expected)
| def test_omit_nuisance_sem(df):
# GH 38774 - sem should work with nuisance columns
| grouped = df.groupby("A")
result = grouped.sem()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem()
tm.assert_frame_equal(result, expected)
| msg = "'DatetimeArray' does not implement reduction 'sum'"
with pytest.raises(TypeError, match=msg):
grouped.agg(lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_sem(df):
# GH 38774 - sem should work with nuisance columns
| 64 | 64 | 70 | 24 | 40 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_omit_nuisance_sem | test_omit_nuisance_sem | 848 | 853 | 848 | 849 | 2060aba0d0c437f6f12c66f80df0f4965628c9ea | bigcode/the-stack | train |
a7112c5de259f5a4666bdc98 | train | function | def test_dont_clobber_name_column():
df = DataFrame(
{"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
| def test_dont_clobber_name_column():
| df = DataFrame(
{"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
| com.asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in expected.items():
assert result[k] == v
_check_groupby(df, result, ["a", "b"], "d")
def test_dont_clobber_name_column():
| 64 | 64 | 79 | 10 | 54 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_dont_clobber_name_column | test_dont_clobber_name_column | 1,391 | 1,397 | 1,391 | 1,391 | 89218c000ff25d95dbf5e2fbcb265d8d7fb661ce | bigcode/the-stack | train |
0d2eb2ef6ad1f5f91026786c | train | function | def test_group_on_two_row_multiindex_returns_one_tuple_key():
# GH 18451
df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}])
df = df.set_index(["a", "b"])
grp = df.groupby(["a", "b"])
result = grp.indices
expected = {(1, 2): np.array([0, 1], dtype=np.int64)}
assert len(r... | def test_group_on_two_row_multiindex_returns_one_tuple_key():
# GH 18451
| df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}])
df = df.set_index(["a", "b"])
grp = df.groupby(["a", "b"])
result = grp.indices
expected = {(1, 2): np.array([0, 1], dtype=np.int64)}
assert len(result) == 1
key = (1, 2)
assert (result[key] == expected[key]).all()
| _items", max_seq_items):
result = df.groupby("a").groups.__repr__()
assert result == expected
result = df.groupby(np.array(df.a)).groups.__repr__()
assert result == expected
def test_group_on_two_row_multiindex_returns_one_tuple_key():
# GH 18451
| 64 | 64 | 144 | 20 | 43 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_group_on_two_row_multiindex_returns_one_tuple_key | test_group_on_two_row_multiindex_returns_one_tuple_key | 2,063 | 2,074 | 2,063 | 2,064 | 4e03080aa1434da0578511e404faa6c4a72bf259 | bigcode/the-stack | train |
8db7763ebe019ca3f4ae3103 | train | function | @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
def test_basic(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in g... | @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
def test_basic(dtype):
| data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
assert len(v) == 3
agged = grouped.aggregate(np.mean)
assert agged[1] == 1
... | Series,
Timestamp,
date_range,
read_csv,
to_datetime,
)
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
def test_repr():
# GH18203
result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=... | 120 | 120 | 400 | 27 | 92 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_basic | test_basic | 36 | 82 | 36 | 38 | b871395b6862810c3a9bd075feaf6283712d548b | bigcode/the-stack | train |
25e4c0367fff56f68a75c2da | train | function | def test_basic_regression():
# regression
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
| def test_basic_regression():
# regression
| result = Series([1.0 * x for x in list(range(1, 10)) * 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
| 3, "b": [1, 2, 3]})
assert len(df.groupby("a")) == 0
assert len(df.groupby("b")) == 3
assert len(df.groupby(["a", "b"])) == 3
def test_basic_regression():
# regression
| 64 | 64 | 70 | 10 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_basic_regression | test_basic_regression | 269 | 277 | 269 | 270 | 8cd3d2891466c27a0fbaf5e7667c4929b207f4f0 | bigcode/the-stack | train |
760c5791a856ae7e47c679bb | train | function | def test_as_index_select_column():
# GH 5764
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
result = df.groupby("A", as_index=False)["B"].get_group(1)
expected = Series([2, 4], name="B")
tm.assert_series_equal(result, expected)
result = df.groupby("A", as_index=False)["B"].apply(l... | def test_as_index_select_column():
# GH 5764
| df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
result = df.groupby("A", as_index=False)["B"].get_group(1)
expected = Series([2, 4], name="B")
tm.assert_series_equal(result, expected)
result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum())
expected = Series(
... | series works the same
result = data["C"].groupby([data["A"], data["B"]]).mean()
expected = data.groupby(["A", "B"]).mean()["C"]
tm.assert_series_equal(result, expected)
def test_as_index_select_column():
# GH 5764
| 64 | 64 | 163 | 14 | 50 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_as_index_select_column | test_as_index_select_column | 607 | 618 | 607 | 608 | c2628005e6d15d01b43502ec2fabfc1bc7e5b546 | bigcode/the-stack | train |
f9175d43058b8289bd8dcb59 | train | function | def test_groupby_multi_corner(df):
# test that having an all-NA column doesn't mess you up
df = df.copy()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
| def test_groupby_multi_corner(df):
# test that having an all-NA column doesn't mess you up
| df = df.copy()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
| tm.assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
tm.assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(df):
# test that having an all-NA column doesn't mess you up
| 64 | 64 | 85 | 23 | 41 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_multi_corner | test_groupby_multi_corner | 811 | 820 | 811 | 812 | 2687b358edf7d858fcfc7880a5282a880448ebf8 | bigcode/the-stack | train |
4d35878548bc73589a9f25f0 | train | function | def test_grouping_ndarray(df):
grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
) # Note: no names when grouping by value
| def test_grouping_ndarray(df):
| grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
) # Note: no names when grouping by value
| )
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df["A", "foo"] = "bar"
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, df.columns[:-1])
def test_grouping_ndarray(df):
| 64 | 64 | 63 | 8 | 56 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_grouping_ndarray | test_grouping_ndarray | 1,040 | 1,047 | 1,040 | 1,040 | 66e27815c65fbd9d04ac83b0b4479ad7d63556c4 | bigcode/the-stack | train |
32dc284cb24c5e66006eb52b | train | function | def test_pass_args_kwargs(ts, tsframe):
def f(x, q=None, axis=0):
return np.percentile(x, q, axis=axis)
g = lambda x: np.percentile(x, 80, axis=0)
# Series
ts_grouped = ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
apply_result = ts_grouped.apply(... | def test_pass_args_kwargs(ts, tsframe):
| def f(x, q=None, axis=0):
return np.percentile(x, q, axis=axis)
g = lambda x: np.percentile(x, 80, axis=0)
# Series
ts_grouped = ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
apply_result = ts_grouped.apply(np.percentile, 80, axis=0)
trans_res... | ("A").first()[["C"]]
e.loc["Pony"] = pd.NaT
tm.assert_frame_equal(result, e)
# scalar outputs
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0].loc["C"]
result = df.groupby("A").apply(f)
e = df.groupby("A").first()["C"].copy()
e.loc["Pony"] = np.... | 126 | 126 | 421 | 10 | 116 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_pass_args_kwargs | test_pass_args_kwargs | 213 | 250 | 213 | 213 | 1654b383414ed56167063f00fdc8dc362fd49e5c | bigcode/the-stack | train |
ad37f354ea851fb1b54193f6 | train | function | def test_groupby_return_type():
# GH2893, return a reduced type
df1 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 2, "val2": 27},
{"val1": 2, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dat... | def test_groupby_return_type():
# GH2893, return a reduced type
| df1 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 2, "val2": 27},
{"val1": 2, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning)... | [group["value"].idxmax()]
applied = df.groupby("A").apply(max_value)
result = applied.dtypes
expected = Series(
[np.dtype("object")] * 2 + [np.dtype("float64")] * 2 + [np.dtype("int64")],
index=["A", "B", "C", "D", "value"],
)
tm.assert_series_equal(result, expected)
def test_groupb... | 108 | 108 | 363 | 18 | 90 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_return_type | test_groupby_return_type | 109 | 148 | 109 | 111 | 4a7390279773535e3f4ea2eda066a8d2b88b4e34 | bigcode/the-stack | train |
91f8ba7261bbf11a35353e29 | train | function | @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
@pytest.mark.parametrize(
"func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
)
def test_groupby_numerical_stability_sum_mean(func, values):
# GH#38778
data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFra... | @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
@pytest.mark.parametrize(
"func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
)
def test_groupby_numerical_stability_sum_mean(func, values):
# GH#38778
| data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
result = getattr(df.groupby("group"), func)()
expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group"))
tm.assert_frame_equal(result, expected)
| @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
@pytest.mark.parametrize(
"func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
)
def test_groupby_numerical_stability_sum_mean(func, values):
# GH#38778
| 82 | 64 | 198 | 82 | 0 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_numerical_stability_sum_mean | test_groupby_numerical_stability_sum_mean | 2,157 | 2,167 | 2,157 | 2,162 | ba37d384d031a267cdb6f9980c0115b2a94cb4bf | bigcode/the-stack | train |
6f47f30fbbe59a3fdc00b3da | train | function | def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
dups = rand_series_with_duplicate_datetimeindex
result = dups.groupby(level=0).mean()
expected = dups.groupby(dups.index).mean()
tm.assert_series_equal(result, expected)
| def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
| dups = rand_series_with_duplicate_datetimeindex
result = dups.groupby(level=0).mean()
expected = dups.groupby(dups.index).mean()
tm.assert_series_equal(result, expected)
| 5e15 + 98] + [97.0, 98.0]
)
expected = DataFrame({"a": exp_data, "b": exp_data})
tm.assert_frame_equal(result, expected, check_exact=True)
def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
| 64 | 64 | 59 | 14 | 50 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_mean_duplicate_index | test_groupby_mean_duplicate_index | 2,183 | 2,187 | 2,183 | 2,183 | b87f793e0ed2d69dee92267ca23fbab626994730 | bigcode/the-stack | train |
fd74fbd2749e9c0006d57068 | train | function | def test_frame_multi_key_function_list():
data = DataFrame(
{
"A": [
"foo",
"foo",
"foo",
"foo",
"bar",
"bar",
"bar",
"bar",
"foo",
"foo... | def test_frame_multi_key_function_list():
| data = DataFrame(
{
"A": [
"foo",
"foo",
"foo",
"foo",
"bar",
"bar",
"bar",
"bar",
"foo",
"foo",
"foo",
],
... | grouped = df.groupby(["k1", "k2"])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(df):
grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected... | 98 | 98 | 327 | 8 | 90 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_frame_multi_key_function_list | test_frame_multi_key_function_list | 513 | 571 | 513 | 513 | 8d6e10ecc5f5131287265ad9f8f41b4979560e4e | bigcode/the-stack | train |
89d694e7fa1ca9c6e678c648 | train | function | @pytest.mark.parametrize("columns", ["C", ["C"]])
@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
@pytest.mark.parametrize(
"values",
[
[True],
[0],
[0.0],
["a"],
[Categorical([0])],
[to_datetime(0)],
[date_range(0, 1, 1, tz="US/Eastern")],
[... | @pytest.mark.parametrize("columns", ["C", ["C"]])
@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
@pytest.mark.parametrize(
"values",
[
[True],
[0],
[0.0],
["a"],
[Categorical([0])],
[to_datetime(0)],
[date_range(0, 1, 1, tz="US/Eastern")],
[... | override_dtype = None
if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply":
# sum/product of bools is an integer
override_dtype = "int64"
df = DataFrame([3 * values], columns=list("ABC"))
df = df.iloc[:0]
gb = df.groupby(keys)[columns]
if method == "at... | @pytest.mark.parametrize("columns", ["C", ["C"]])
@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
@pytest.mark.parametrize(
"values",
[
[True],
[0],
[0.0],
["a"],
[Categorical([0])],
[to_datetime(0)],
[date_range(0, 1, 1, tz="US/Eastern")],
[... | 184 | 104 | 349 | 184 | 0 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_empty_groupby | test_empty_groupby | 1,721 | 1,762 | 1,721 | 1,742 | 6b23633fee2d7575c4022ff77f169cf46587e5d6 | bigcode/the-stack | train |
0e92db6dd7e2813fdfd7f5d6 | train | function | def test_groupby_2d_malformed():
d = DataFrame(index=range(2))
d["group"] = ["g1", "g2"]
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
tmp = d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["z... | def test_groupby_2d_malformed():
| d = DataFrame(index=range(2))
d["group"] = ["g1", "g2"]
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
tmp = d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
tm.assert_nu... | df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
result = df.groupby(["a", "b"]).indices
assert result == {}
def test_groupby_2d_malformed():
| 63 | 64 | 133 | 10 | 53 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_2d_malformed | test_groupby_2d_malformed | 1,328 | 1,337 | 1,328 | 1,328 | ce2140ee9ef2c0ffe0f13793d874f95385fff8ee | bigcode/the-stack | train |
4702db9652c11fff66af1eec | train | function | def test_groupby_nonstring_columns():
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
| def test_groupby_nonstring_columns():
| df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
| assert metrics.columns.name is None
metrics = df.groupby("A").apply(summarize, "metrics")
assert metrics.columns.name == "metrics"
metrics = df.groupby("A").apply(summarize_random_name)
assert metrics.columns.name is None
def test_groupby_nonstring_columns():
| 64 | 64 | 60 | 8 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_nonstring_columns | test_groupby_nonstring_columns | 1,126 | 1,131 | 1,126 | 1,126 | 5f71ae4ab7c3999eff7fce92b20be443913340e1 | bigcode/the-stack | train |
ab149d4fbe04a5c7cccd9272 | train | function | def test_inconsistent_return_type():
# GH5592
# inconsistent return type
df = DataFrame(
{
"A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
"B": Series(np.arange(7), dtype="int64"),
"C": date_range("20130101", periods=7),
}
)
def ... | def test_inconsistent_return_type():
# GH5592
# inconsistent return type
| df = DataFrame(
{
"A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
"B": Series(np.arange(7), dtype="int64"),
"C": date_range("20130101", periods=7),
}
)
def f(grp):
return grp.iloc[0]
expected = df.groupby("A").first()[["B"]]... | .assert_produces_warning(FutureWarning):
result = df2.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
# GH3596, return a consistent type (regression in 0.11 from 0.10.1)
df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"])
with tm.assert_produces_warning(FutureWarnin... | 134 | 134 | 447 | 19 | 115 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_inconsistent_return_type | test_inconsistent_return_type | 151 | 210 | 151 | 153 | a50754c6d2e78511f2ca10d759ad48a8acf46e28 | bigcode/the-stack | train |
5dfa5adb68742dc0cdcc1d46 | train | function | def test_groupby_duplicate_index():
# GH#29189 the groupby call here used to raise
ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
gb = ser.groupby(level=0)
result = gb.mean()
expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
tm.assert_series_equal(result, expected)
| def test_groupby_duplicate_index():
# GH#29189 the groupby call here used to raise
| ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
gb = ser.groupby(level=0)
result = gb.mean()
expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
tm.assert_series_equal(result, expected)
| "x": 1})
actual = df.groupby("g")["x"].transform("sum")
expected = Series([np.nan], name="x")
tm.assert_series_equal(actual, expected)
def test_groupby_duplicate_index():
# GH#29189 the groupby call here used to raise
| 64 | 64 | 114 | 22 | 42 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_groupby_duplicate_index | test_groupby_duplicate_index | 1,971 | 1,978 | 1,971 | 1,972 | 8d73cc2b43f4e54dae1eb6fded48b25a2906d467 | bigcode/the-stack | train |
2b7cb4f3a1be955829899adf | train | function | @pytest.mark.parametrize(
"klass, attr, value",
[
(DataFrame, "level", "a"),
(DataFrame, "as_index", False),
(DataFrame, "sort", False),
(DataFrame, "group_keys", False),
(DataFrame, "squeeze", True),
(DataFrame, "observed", True),
(DataFrame, "dropna", Fa... | @pytest.mark.parametrize(
"klass, attr, value",
[
(DataFrame, "level", "a"),
(DataFrame, "as_index", False),
(DataFrame, "sort", False),
(DataFrame, "group_keys", False),
(DataFrame, "squeeze", True),
(DataFrame, "observed", True),
(DataFrame, "dropna", Fa... | df = DataFrame({"a": [1], "b": [2], "c": [3]})
if attr != "axis":
df = df.set_index("a")
expected = df.groupby("a", **{attr: value})
result = expected[["b"]] if klass is DataFrame else expected["b"]
assert getattr(result, attr) == getattr(expected, attr)
| @pytest.mark.parametrize(
"klass, attr, value",
[
(DataFrame, "level", "a"),
(DataFrame, "as_index", False),
(DataFrame, "sort", False),
(DataFrame, "group_keys", False),
(DataFrame, "squeeze", True),
(DataFrame, "observed", True),
(DataFrame, "dropna", Fa... | 257 | 102 | 342 | 257 | 0 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_subsetting_columns_keeps_attrs | test_subsetting_columns_keeps_attrs | 2,077 | 2,115 | 2,077 | 2,108 | 6204050fdb4b7758045e2cfbf7622f3903f969c4 | bigcode/the-stack | train |
67fad9a3f383b23d29b643fe | train | function | def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
df = DataFrame(
{
("a", "b"): [1, 1, 1, 1],
"a": [2, 2, 2, 2],
"b": [2, 2, 2, 2],
"c": [1, 1, 1, 1],
}
)
with pytest.raises(KeyError, match=r"('a', 'b')"):
... | def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
| df = DataFrame(
{
("a", "b"): [1, 1, 1, 1],
"a": [2, 2, 2, 2],
"b": [2, 2, 2, 2],
"c": [1, 1, 1, 1],
}
)
with pytest.raises(KeyError, match=r"('a', 'b')"):
df[["a", "b", "c"]].groupby(("a", "b"))
result = df.groupby(("a", "b"))["c... | override_dtype is not None:
expected = expected.astype(override_dtype)
if len(keys) == 1:
expected.index.name = keys[0]
tm.assert_equal(result, expected)
def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
| 64 | 64 | 189 | 23 | 41 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_tuple_as_grouping | test_tuple_as_grouping | 1,765 | 1,781 | 1,765 | 1,766 | d4f49ffd0a484de579b1de9a08a77670c6262499 | bigcode/the-stack | train |
c16fd3fca6b6d96dce7b55d9 | train | function | def test_index_label_overlaps_location():
# checking we don't have any label/location confusion in the
# wake of GH5375
df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equ... | def test_index_label_overlaps_location():
# checking we don't have any label/location confusion in the
# wake of GH5375
| df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expecte... | tm.assert_frame_equal(expected, result)
result = (
df.sort_index()
.groupby(level=level, sort=sort)
.apply(DataFrame.drop_duplicates)
)
expected = df.sort_index()
tm.assert_frame_equal(expected, result)
def test_index_labe... | 84 | 84 | 282 | 29 | 55 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_index_label_overlaps_location | test_index_label_overlaps_location | 1,627 | 1,653 | 1,627 | 1,629 | 377220a56db02a3b8fd63f94cff65b7fdd2ad32e | bigcode/the-stack | train |
2d4097dbd648f4c1d4b6ae5d | train | function | @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
def test_bool_aggs_dup_column_labels(bool_agg_func):
# 21668
df = DataFrame([[True, True]], columns=["a", "a"])
grp_by = df.groupby([0])
result = getattr(grp_by, bool_agg_func)()
expected = df
tm.assert_frame_equal(result, expected)
| @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
def test_bool_aggs_dup_column_labels(bool_agg_func):
# 21668
| df = DataFrame([[True, True]], columns=["a", "a"])
grp_by = df.groupby([0])
result = getattr(grp_by, bool_agg_func)()
expected = df
tm.assert_frame_equal(result, expected)
| 5, 8], index=[2.0, 4.0, 5.0])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
def test_bool_aggs_dup_column_labels(bool_agg_func):
# 21668
| 64 | 64 | 88 | 34 | 30 | Pawel-Kranzberg/pandas | pandas/tests/groupby/test_groupby.py | Python | test_bool_aggs_dup_column_labels | test_bool_aggs_dup_column_labels | 1,981 | 1,989 | 1,981 | 1,983 | 9548cbabf99eeeb35e0fcb69b9438ac5ccb799fd | bigcode/the-stack | train |
1b689169fcd577eb142059c5 | train | function | def scan(ip):
arp_request = scapy.ARP(pdst=ip)
# use custom Ether to capture MAC of the broadcast
broadcast = scapy.Ether\
(dst='ff:ff:ff:ff:ff:ff')
arp_request_broadcast = \
broadcast / arp_request
# srp return 2 list answered and unanswered list
answered_list = scapy.srp(arp_r... | def scan(ip):
| arp_request = scapy.ARP(pdst=ip)
# use custom Ether to capture MAC of the broadcast
broadcast = scapy.Ether\
(dst='ff:ff:ff:ff:ff:ff')
arp_request_broadcast = \
broadcast / arp_request
# srp return 2 list answered and unanswered list
answered_list = scapy.srp(arp_request_broadca... | /bin/env python3
import scapy.all as scapy
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", dest="target", help="Target IP / IP range.")
options = parser.parse_args()
return options
def scan(ip):
| 64 | 64 | 145 | 4 | 59 | jackyhuynh/ethical-hacking-using-python | src/network-scanner/network-scanner.py | Python | scan | scan | 13 | 29 | 13 | 13 | 43cf365e4c9e7b139b9ce28db48fd5d82b29cc60 | bigcode/the-stack | train |
45ae210bc42dfec69c663b44 | train | function | def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", dest="target", help="Target IP / IP range.")
options = parser.parse_args()
return options
| def get_arguments():
| parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", dest="target", help="Target IP / IP range.")
options = parser.parse_args()
return options
| #!/usr/bin/env python3
import scapy.all as scapy
import argparse
def get_arguments():
| 22 | 64 | 44 | 4 | 17 | jackyhuynh/ethical-hacking-using-python | src/network-scanner/network-scanner.py | Python | get_arguments | get_arguments | 6 | 10 | 6 | 6 | 8f29af42b416f2984887b646b26f17e9dbe2dac2 | bigcode/the-stack | train |
a4ddedcbb1da9ee34c16e31a | train | function | def print_result(answered_list):
print("IP\t\t\t\tMAC ADDRESS\n--------------------------------------------")
for answer in answered_list:
print(answer['ip'] + "\t\t" + answer['mac'])
| def print_result(answered_list):
| print("IP\t\t\t\tMAC ADDRESS\n--------------------------------------------")
for answer in answered_list:
print(answer['ip'] + "\t\t" + answer['mac'])
| arp_request_broadcast,
timeout=1, verbose=False)[0]
client_list = []
for answer in answered_list:
client_list.append({"ip": answer[1].psrc,
"mac": answer[1].hwsrc})
return client_list
def print_result(answered_list):
| 64 | 64 | 44 | 7 | 56 | jackyhuynh/ethical-hacking-using-python | src/network-scanner/network-scanner.py | Python | print_result | print_result | 32 | 35 | 32 | 32 | 0b72de766aba1a21f7de8fa804cb0f572ee81240 | bigcode/the-stack | train |
22942e34039ea5e8712d9d73 | train | class | class Snapshot(Animation):
def __init__(self, name: str):
self._name = name
def dump(self):
return self._name
def build(self):
raise NotImplementedError("Snapshot cannot be merged with other Animations")
| class Snapshot(Animation):
| def __init__(self, name: str):
self._name = name
def dump(self):
return self._name
def build(self):
raise NotImplementedError("Snapshot cannot be merged with other Animations")
| ": self}
class Config(dict, Animation):
def build(self):
return {"config": self}
class Style(Animation):
def __init__(self, data: typing.Optional[dict]):
self._data = data
def build(self):
return {"style": self._data}
class Snapshot(Animation):
| 64 | 64 | 53 | 4 | 60 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Snapshot | Snapshot | 203 | 211 | 203 | 203 | 07f3f481e00f2f543b70625e85644dff102e49e1 | bigcode/the-stack | train |
6d470237974f00ea068eac71 | train | class | class Config(dict, Animation):
def build(self):
return {"config": self}
| class Config(dict, Animation):
| def build(self):
return {"config": self}
| kwargs}
if values is not None:
value["values"] = values
self._add_value(dest, value)
def _add_value(self, dest, value):
self.setdefault(dest, []).append(value)
def build(self):
return {"data": self}
class Config(dict, Animation):
| 64 | 64 | 18 | 6 | 58 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Config | Config | 190 | 192 | 190 | 190 | 80844d8c44030f6dbeed9e37858c588c14fcacd5 | bigcode/the-stack | train |
4349f01d227d232fb95d3008 | train | class | class Data(dict, Animation):
"""
Vizzu data with the required keys: records, series, dimensions or measures.
"""
@classmethod
def from_json(cls, filename):
with open(filename, "r", encoding="utf8") as file_desc:
return cls(json.load(file_desc))
def add_record(self, record):... | class Data(dict, Animation):
| """
Vizzu data with the required keys: records, series, dimensions or measures.
"""
@classmethod
def from_json(cls, filename):
with open(filename, "r", encoding="utf8") as file_desc:
return cls(json.load(file_desc))
def add_record(self, record):
self._add_value("rec... | )
FEATURE = _SCRIPT.format(
"""
myVizzu_{id}.parentNode.parentNode.style.display = "none";
chart_{c_id} = chart_{c_id}.then(chart => {{
{feature};
return chart;
}});
"""
)
class Animation:
def dump(self):
ret... | 130 | 130 | 435 | 6 | 123 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Data | Data | 136 | 187 | 136 | 136 | 9157d36823ac7179906761e1f2bfccd2c87b3e8f | bigcode/the-stack | train |
f7e9be674e01bdee704cc535 | train | class | class DisplayTemplate:
_SCRIPT = """
<script id="myVizzu_{{id}}">
{}
</script>
"""
_NEW_CHART = """
let myVizzu_{c_id} = document.createElement("div");
myVizzu_{c_id}.style.cssText = "width: {div_width}; height: {div_height};";
let chart_... | class DisplayTemplate:
| _SCRIPT = """
<script id="myVizzu_{{id}}">
{}
</script>
"""
_NEW_CHART = """
let myVizzu_{c_id} = document.createElement("div");
myVizzu_{c_id}.style.cssText = "width: {div_width}; height: {div_height};";
let chart_{c_id} = import("{vizzu}... | """
Jupyter notebook integration for Vizzu.
"""
import json
import abc
import typing
import uuid
import enum
import numpy as np
from inspect import cleandoc
from textwrap import indent, dedent
from IPython.display import display_html
class DisplayTarget(str, enum.Enum):
BEGIN = "begin"
END = "end"
ACTU... | 85 | 220 | 734 | 4 | 81 | csaladenes/ipyvizzu | ipyvizzu.py | Python | DisplayTemplate | DisplayTemplate | 24 | 117 | 24 | 25 | 578134d8e68ded4edee99480d8f65216ea90e067 | bigcode/the-stack | train |
50a43a65cd756bf3dc513ef1 | train | class | class Style(Animation):
def __init__(self, data: typing.Optional[dict]):
self._data = data
def build(self):
return {"style": self._data}
| class Style(Animation):
| def __init__(self, data: typing.Optional[dict]):
self._data = data
def build(self):
return {"style": self._data}
|
self._add_value(dest, value)
def _add_value(self, dest, value):
self.setdefault(dest, []).append(value)
def build(self):
return {"data": self}
class Config(dict, Animation):
def build(self):
return {"config": self}
class Style(Animation):
| 64 | 64 | 39 | 4 | 60 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Style | Style | 195 | 200 | 195 | 195 | c863fda7b684297cc76068ef86528188bd497181 | bigcode/the-stack | train |
08f005760844e6e3e22df80a | train | class | class PlainAnimation(dict, Animation):
def build(self):
return self
| class PlainAnimation(dict, Animation):
| def build(self):
return self
| }});
"""
)
class Animation:
def dump(self):
return json.dumps(self.build())
@abc.abstractmethod
def build(self) -> typing.Mapping:
"""
Return a dict with native python values that can be converted into json.
"""
class PlainAnimation(dict, Animat... | 63 | 64 | 16 | 7 | 56 | csaladenes/ipyvizzu | ipyvizzu.py | Python | PlainAnimation | PlainAnimation | 131 | 133 | 131 | 131 | 4509541c4938d13b1ae72851494bdec2197fc818 | bigcode/the-stack | train |
488055ec6ab67f87920cb5e1 | train | class | class Feature(Method):
def __init__(self, name, value):
self._name = name
self._value = value
def dump(self):
name = json.dumps(self._name)
value = json.dumps(self._value)
return f"chart.feature({name}, {value})"
| class Feature(Method):
| def __init__(self, name, value):
self._name = name
self._value = value
def dump(self):
name = json.dumps(self._name)
value = json.dumps(self._value)
return f"chart.feature({name}, {value})"
| option=None):
self._data = data
self._option = option
def dump(self):
data = self._data.dump()
if self._option:
data += ", " + PlainAnimation(self._option).dump()
return f"chart.animate({data})"
class Feature(Method):
| 64 | 64 | 65 | 4 | 60 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Feature | Feature | 250 | 258 | 250 | 250 | d1696f4f818835f9eeb8587bd7772b12ef577314 | bigcode/the-stack | train |
beb5b8f91196a355b178dad2 | train | class | class Animate(Method):
def __init__(self, data, option=None):
self._data = data
self._option = option
def dump(self):
data = self._data.dump()
if self._option:
data += ", " + PlainAnimation(self._option).dump()
return f"chart.animate({data})"
| class Animate(Method):
| def __init__(self, data, option=None):
self._data = data
self._option = option
def dump(self):
data = self._data.dump()
if self._option:
data += ", " + PlainAnimation(self._option).dump()
return f"chart.animate({data})"
| , animation):
data = animation.build()
common_keys = set(data).intersection(self)
if common_keys:
raise ValueError(f"Animation is already merged: {common_keys}")
return data
class Method:
@abc.abstractmethod
def dump(self):
pass
class Animate(Method):
| 64 | 64 | 73 | 4 | 59 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Animate | Animate | 238 | 247 | 238 | 238 | 6fab3dac9ce1fe4471d98dd061da36f0eacf4bcd | bigcode/the-stack | train |
d47fc0b19ae9e09e45d72f25 | train | class | class DisplayTarget(str, enum.Enum):
BEGIN = "begin"
END = "end"
ACTUAL = "actual"
| class DisplayTarget(str, enum.Enum):
| BEGIN = "begin"
END = "end"
ACTUAL = "actual"
| """
Jupyter notebook integration for Vizzu.
"""
import json
import abc
import typing
import uuid
import enum
import numpy as np
from inspect import cleandoc
from textwrap import indent, dedent
from IPython.display import display_html
class DisplayTarget(str, enum.Enum):
| 62 | 64 | 27 | 8 | 53 | csaladenes/ipyvizzu | ipyvizzu.py | Python | DisplayTarget | DisplayTarget | 17 | 21 | 17 | 18 | 1d53513fb8293c91d4ba6f5d12f66219518acc34 | bigcode/the-stack | train |
562c5e7a1e73a8162e39ecfd | train | class | class Method:
@abc.abstractmethod
def dump(self):
pass
| class Method:
@abc.abstractmethod
| def dump(self):
pass
| (animation)
self.update(data)
def _validate(self, animation):
data = animation.build()
common_keys = set(data).intersection(self)
if common_keys:
raise ValueError(f"Animation is already merged: {common_keys}")
return data
class Method:
@abc.abstractmethod
| 64 | 64 | 17 | 9 | 54 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Method | Method | 232 | 235 | 232 | 233 | ab2768e077980dec5ec872b46af989a9273224b2 | bigcode/the-stack | train |
a8d4459a04713039a63e0f03 | train | class | class Animation:
def dump(self):
return json.dumps(self.build())
@abc.abstractmethod
def build(self) -> typing.Mapping:
"""
Return a dict with native python values that can be converted into json.
"""
| class Animation:
| def dump(self):
return json.dumps(self.build())
@abc.abstractmethod
def build(self) -> typing.Mapping:
"""
Return a dict with native python values that can be converted into json.
"""
| """
)
FEATURE = _SCRIPT.format(
"""
myVizzu_{id}.parentNode.parentNode.style.display = "none";
chart_{c_id} = chart_{c_id}.then(chart => {{
{feature};
return chart;
}});
"""
)
class Animation:
| 64 | 64 | 49 | 3 | 61 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Animation | Animation | 120 | 128 | 120 | 120 | 077f3ee3dfd6ed62e0381fe8ec9e8ec03f129e5d | bigcode/the-stack | train |
72f774052d589cf2e53fbe4c | train | class | class Chart:
"""
Wrapper over Vizzu Chart
"""
VIZZU = "https://cdn.jsdelivr.net/npm/vizzu@~0.4.0/dist/vizzu.min.js"
def __init__(
self,
vizzu=VIZZU,
width="800px",
height="480px",
display: DisplayTarget = DisplayTarget("actual"),
):
self._c_id = ... | class Chart:
| """
Wrapper over Vizzu Chart
"""
VIZZU = "https://cdn.jsdelivr.net/npm/vizzu@~0.4.0/dist/vizzu.min.js"
def __init__(
self,
vizzu=VIZZU,
width="800px",
height="480px",
display: DisplayTarget = DisplayTarget("actual"),
):
self._c_id = uuid.uuid4().... | dump(self):
data = self._data.dump()
if self._option:
data += ", " + PlainAnimation(self._option).dump()
return f"chart.animate({data})"
class Feature(Method):
def __init__(self, name, value):
self._name = name
self._value = value
def dump(self):
n... | 157 | 157 | 524 | 3 | 153 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Chart | Chart | 269 | 351 | 269 | 269 | 1775fc03e65088d81963fe2cdb7a7f4e34588106 | bigcode/the-stack | train |
7d2c5698f1c7af01df204bbc | train | class | class AnimationMerger(dict, Animation):
def build(self):
return self
def merge(self, animation: Animation):
data = self._validate(animation)
self.update(data)
def _validate(self, animation):
data = animation.build()
common_keys = set(data).intersection(self)
... | class AnimationMerger(dict, Animation):
| def build(self):
return self
def merge(self, animation: Animation):
data = self._validate(animation)
self.update(data)
def _validate(self, animation):
data = animation.build()
common_keys = set(data).intersection(self)
if common_keys:
raise Valu... | ._data}
class Snapshot(Animation):
def __init__(self, name: str):
self._name = name
def dump(self):
return self._name
def build(self):
raise NotImplementedError("Snapshot cannot be merged with other Animations")
class AnimationMerger(dict, Animation):
| 64 | 64 | 87 | 8 | 56 | csaladenes/ipyvizzu | ipyvizzu.py | Python | AnimationMerger | AnimationMerger | 214 | 229 | 214 | 214 | 8f7c9b5fb9eb8e3f50ead96ac0fb61597e65e362 | bigcode/the-stack | train |
d20c6a82669170fdf41566f1 | train | class | class Store(Method):
def __init__(self, snapshot_name: str):
self._snaphot_name = snapshot_name
def dump(self):
return f"{self._snaphot_name} = chart.store();"
| class Store(Method):
| def __init__(self, snapshot_name: str):
self._snaphot_name = snapshot_name
def dump(self):
return f"{self._snaphot_name} = chart.store();"
| def __init__(self, name, value):
self._name = name
self._value = value
def dump(self):
name = json.dumps(self._name)
value = json.dumps(self._value)
return f"chart.feature({name}, {value})"
class Store(Method):
| 64 | 64 | 48 | 4 | 60 | csaladenes/ipyvizzu | ipyvizzu.py | Python | Store | Store | 261 | 266 | 261 | 261 | dcd743ab02054b317084e353a856537649992b25 | bigcode/the-stack | train |
03b1906e8e0a3d13dbfdacf0 | train | function | def test_query_stackoverflow(capsys: "pytest.CaptureFixture[str]") -> None:
simple_app.query_stackoverflow()
out, _ = capsys.readouterr()
assert "views" in out
| def test_query_stackoverflow(capsys: "pytest.CaptureFixture[str]") -> None:
| simple_app.query_stackoverflow()
out, _ = capsys.readouterr()
assert "views" in out
| OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import typing
import simple_app
if typing.TYPE_CHECKING:
import pytest
def test_query_stackoverflow(capsys: "pytest.CaptureFixture[str]") -> None:
| 64 | 64 | 46 | 20 | 43 | KoffieLabs/python-bigquery | samples/snippets/simple_app_test.py | Python | test_query_stackoverflow | test_query_stackoverflow | 23 | 26 | 23 | 23 | 31b81b9a8cf1869ba8568e7f799cb4ca37adba00 | bigcode/the-stack | train |
866c335cbcdceca02981993c | train | class | class RReportingtools(RPackage):
"""The ReportingTools software package enables users to easily
display reports of analysis results generated from sources such
as microarray and sequencing data. The package allows users to
create HTML pages that may be viewed on a web browser such as
Safari, or in o... | class RReportingtools(RPackage):
| """The ReportingTools software package enables users to easily
display reports of analysis results generated from sources such
as microarray and sequencing data. The package allows users to
create HTML pages that may be viewed on a web browser such as
Safari, or in other formats readable by programs... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RReportingtools(RPackage):
| 61 | 175 | 585 | 7 | 54 | RemoteConnectionManager/spack | var/spack/repos/builtin/packages/r-reportingtools/package.py | Python | RReportingtools | RReportingtools | 9 | 48 | 9 | 9 | b5606673f2abfae4b1519cad5966fa673a95c097 | bigcode/the-stack | train |
c544d2ffd0ebdf09b8225c62 | train | function | def _build_relabel_dict(root, conn, depth, actions, observations, max_depth=None, visit_threshold=0):
"""Traverse the tree and collect unique actions and observations,
store them in dictionaries `actions` and `observations`. Requires
all observations and actions to be hashable."""
if max_depth is not No... | def _build_relabel_dict(root, conn, depth, actions, observations, max_depth=None, visit_threshold=0):
| """Traverse the tree and collect unique actions and observations,
store them in dictionaries `actions` and `observations`. Requires
all observations and actions to be hashable."""
if max_depth is not None and depth >= max_depth:
return
if conn is not None:
if isinstance(root, VNode):... | =max_value, min_value=min_value,
max_depth=max_depth, visit_threshold=visit_threshold,
relabel_actions=relabel_actions, relabel_observations=relabel_observations)
def _build_relabel_dict(root, conn, depth, actions, observations, max_depth=None, visit_threshold=0):
| 64 | 64 | 190 | 25 | 39 | beckymathew/pomdp-py | pomdp_py/algorithms/visual/visual.py | Python | _build_relabel_dict | _build_relabel_dict | 43 | 58 | 43 | 43 | 0550297f42bb275431f8eaeee480195588051f62 | bigcode/the-stack | train |
4a89ff19f1713d4e06354f5f | train | function | def _build_graph(G, root, parent, conn, depth,
max_depth=None, visit_threshold=0,
max_value=None, min_value=None,
relabel_actions={},
relabel_observations={}):
if max_depth is not None and depth >= max_depth:
return
G.add_node(root)
... | def _build_graph(G, root, parent, conn, depth,
max_depth=None, visit_threshold=0,
max_value=None, min_value=None,
relabel_actions={},
relabel_observations={}):
| if max_depth is not None and depth >= max_depth:
return
G.add_node(root)
if parent is not None:
if isinstance(root, VNode):
if len(relabel_observations) > 0:
conn = relabel_observations[conn]
else:
if len(relabel_actions) > 0:
c... | import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
from pomdp_py import QNode, VNode, RootVNode, util
# ---- POMCP Visualization ---- #
def _build_graph(G, root, parent, conn, depth,
max_depth=None, visit_threshold=0,
max_value... | 97 | 98 | 329 | 47 | 50 | beckymathew/pomdp-py | pomdp_py/algorithms/visual/visual.py | Python | _build_graph | _build_graph | 8 | 41 | 8 | 12 | 76dbd40a3488945b31cf22b7ed91901714b167e8 | bigcode/the-stack | train |
4bf8eed1c59348c864464cef | train | function | def visualize_pouct_search_tree(root, max_depth=1,
visit_threshold=1, anonymize=False,
anonymize_actions=False, anonymize_observations=False,
output_file=None, use_dot=False, ax=None):
"""
Visualize the given tree up... | def visualize_pouct_search_tree(root, max_depth=1,
visit_threshold=1, anonymize=False,
anonymize_actions=False, anonymize_observations=False,
output_file=None, use_dot=False, ax=None):
| """
Visualize the given tree up to depth `max_depth`. Display nodes
with number of visits >= `visit_threshold`.
If anonymize is True, will only display actions as a1,a2,... and observations
as o1,o2,... .
"""
relabel_actions = {}
relabel_observations = {}
if anonymize:
anony... | conn, depth, actions, observations, max_depth=None, visit_threshold=0):
"""Traverse the tree and collect unique actions and observations,
store them in dictionaries `actions` and `observations`. Requires
all observations and actions to be hashable."""
if max_depth is not None and depth >= max_depth:
... | 231 | 231 | 771 | 49 | 182 | beckymathew/pomdp-py | pomdp_py/algorithms/visual/visual.py | Python | visualize_pouct_search_tree | visualize_pouct_search_tree | 60 | 133 | 60 | 63 | 6a8549c5508d7d5cc63e57d77033acbd944bb33d | bigcode/the-stack | train |
235e7ec7f7983fd4aa742d0c | train | class | class ImportsParser(object):
def __init__(self, rawcode_callback=None):
self._modules = []
self._rawcode_callback = rawcode_callback
def parse(self, content, fpath, lineno):
parsed = ast.parse(content)
self._fpath = fpath
self._mods = fpath[:-3].split("/")
self._... | class ImportsParser(object):
| def __init__(self, rawcode_callback=None):
self._modules = []
self._rawcode_callback = rawcode_callback
def parse(self, content, fpath, lineno):
parsed = ast.parse(content)
self._fpath = fpath
self._mods = fpath[:-3].split("/")
self._lineno = lineno - 1
s... | .extend(parse_file_imports(fpath, code))
if has_py:
user_modules.add(trim_suffix(dirpath, "/"))
return imported_modules, user_modules
def _read_code(fpath):
if fpath.endswith(".ipynb"):
nb = nbformat.read(fpath, as_version=4)
code = ""
for cell in nb.cells:
... | 256 | 256 | 1,443 | 5 | 250 | vishalsrao/pigar | pigar/parser.py | Python | ImportsParser | ImportsParser | 88 | 252 | 88 | 88 | 216740b237643743938b84f9112020b2fc69cec2 | bigcode/the-stack | train |
c3e5b2feb86a10f7e252bcb8 | train | function | def parse_imports(package_root, ignores=None):
"""package_root must be a absolute path to package root,
e.g. /path/to/pigar/pigar."""
ignores = set(ignores) if ignores else set()
ignores |= set([".hg", ".svn", ".git", "__pycache__"])
ignored_paths = collections.defaultdict(set)
for path in ignor... | def parse_imports(package_root, ignores=None):
| """package_root must be a absolute path to package root,
e.g. /path/to/pigar/pigar."""
ignores = set(ignores) if ignores else set()
ignores |= set([".hg", ".svn", ".git", "__pycache__"])
ignored_paths = collections.defaultdict(set)
for path in ignores:
path = trim_suffix(path, "/")
... | import print_function, division, absolute_import
import os
import sys
import fnmatch
import ast
import doctest
import collections
import os.path as pathlib
from .log import logger
from .helpers import parse_git_config, trim_suffix
import nbformat
Module = collections.namedtuple('Module', ['name', 'try_', 'file', '... | 87 | 88 | 296 | 10 | 77 | vishalsrao/pigar | pigar/parser.py | Python | parse_imports | parse_imports | 21 | 55 | 21 | 21 | 9ee69b117cccca7f5e082082c21a21df54a51216 | bigcode/the-stack | train |
2545150282961e91e759a7ed | train | function | def parse_file_imports(fpath, content):
py_codes = collections.deque([(content, 1)])
parser = ImportsParser(
lambda code, lineno: py_codes.append((code, lineno)) # noqa
)
while py_codes:
code, lineno = py_codes.popleft()
try:
parser.parse(code, fpath, lineno)
... | def parse_file_imports(fpath, content):
| py_codes = collections.deque([(content, 1)])
parser = ImportsParser(
lambda code, lineno: py_codes.append((code, lineno)) # noqa
)
while py_codes:
code, lineno = py_codes.popleft()
try:
parser.parse(code, fpath, lineno)
except SyntaxError as e:
#... | nb.cells:
if cell.cell_type == "code":
code += cell.source + "\n"
return code
elif fpath.endswith(".py"):
with open(fpath, 'rb') as f:
return f.read()
return None
def parse_file_imports(fpath, content):
| 64 | 64 | 124 | 10 | 53 | vishalsrao/pigar | pigar/parser.py | Python | parse_file_imports | parse_file_imports | 72 | 85 | 72 | 72 | 6b23b9ebc3ae36ffc1ceca16f6c2ff599e572096 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.