Pandas DataFrame 数组测试

本文通过几个具体的示例展示了如何使用 Python 的 Pandas 库进行数据操作,包括 Series 和 DataFrame 的加法运算,以及不同索引之间的运算处理。这些示例有助于理解 Pandas 中的数据结构及其基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    s = pd.Series([1, 2, 3, 4])
    df = pd.DataFrame({
        0: [10, 20, 30, 40],
        1: [50, 60, 70, 80],
        2: [90, 100, 110, 120],
        3: [130, 140, 150, 160]
    })
    
    print df + 7
    print df + s
    print df + df
    0   1    2    3
0  17  57   97  137
1  27  67  107  147
2  37  77  117  157
3  47  87  127  167
    0   1    2    3
0  11  52   93  134
1  21  62  103  144
2  31  72  113  154
3  41  82  123  164
    0    1    2    3
0  20  100  180  260
1  40  120  200  280
2  60  140  220  300
3  80  160  240  320
    s = pd.Series([1, 2, 3, 4])
    df = pd.DataFrame({0: [10], 1: [20], 2: [30], 3: [40]})
    
    print df
    print df + s
    0   1   2   3
0  10  20  30  40

    0   1   2   3
0  11  22  33  44

    s = pd.Series([1, 2, 3, 4])
    df = pd.DataFrame({0: [10, 20, 30, 40]})
    
    print df
    print df + s
    0
0  10
1  20
2  30
3  40

    0   1   2   3
0  11 NaN NaN NaN
1  21 NaN NaN NaN
2  31 NaN NaN NaN
3  41 NaN NaN NaN
    s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
    df = pd.DataFrame({
        'a': [10, 20, 30, 40],
        'b': [50, 60, 70, 80],
        'c': [90, 100, 110, 120],
        'd': [130, 140, 150, 160]
    })
    
    print df
    print df + s
    a   b    c    d
0  10  50   90  130
1  20  60  100  140
2  30  70  110  150
3  40  80  120  160

    a   b    c    d
0  11  52   93  134
1  21  62  103  144
2  31  72  113  154
3  41  82  123  164
    s = pd.Series([1, 2, 3, 4])
    df = pd.DataFrame({
        'a': [10, 20, 30, 40],
        'b': [50, 60, 70, 80],
        'c': [90, 100, 110, 120],
        'd': [130, 140, 150, 160]
    })
    
    print df
    print df + s
    a   b    c    d
0  10  50   90  130
1  20  60  100  140
2  30  70  110  150
3  40  80  120  160

    0   1   2   3   a   b   c   d
0 NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN









### 处理三维数据的Pandas DataFrame 使用方法 #### 将三维 NumPy 数组转换为嵌套 Pandas DataFrame 为了将三维NumPy数组转换成可以被Pandas处理的形式,一种常见的方式是创建一个嵌套的数据框。这意味着每一行代表原始3D数组的一个切片,并且该切片本身作为另一个DataFrame存储在主DataFrame中的单元格内。 ```python import numpy as np import pandas as pd def array_to_nested_df(array_3d): """Converts a 3-dimensional numpy array into a nested pandas DataFrame.""" n_samples, height, width = array_3d.shape dataframes_list = [] for i in range(n_samples): sample_array = array_3d[i,:,:].flatten() temp_df = pd.DataFrame(sample_array.reshape(-1,height)) dataframes_list.append(temp_df) result_df = pd.concat(dataframes_list, keys=range(len(dataframes_list)), axis=0) return result_df.unstack(level=-1)[^1] array_example = np.random.rand(5,4,3) # 创建一个随机的三维数组用于测试 nested_dataframe = array_to_nested_df(array_example) print(nested_dataframe.head()) ``` 这种方法适用于当每个时间序列或其他类型的观测值集合作为代表单一样本的一整个矩阵时的情况。 #### 构建具有多重索引(MultiIndex) 的 Pandas DataFrame 来表示三维数据 另一种方式是以多层索引来表达第三维度的信息,这使得可以直接访问特定位置上的数值而无需解包更复杂的对象: ```python shape_x, shape_y, shape_z = (10, 10, 10) multi_indexed_data = np.arange(shape_x * shape_y * shape_z).reshape((shape_x, shape_y, shape_z)) arrays_for_mi = [ ['x_%d' % i]*shape_y*shape_z + list(range(shape_y))*shape_z + list(range(shape_z))* shape_x*shape_y, sum([[f'y_{j}' for _ in range(shape_z)]for j in range(shape_y)], []), [str(k) for k in range(shape_z)*shape_x*shape_y] ] df_with_multiindex = pd.DataFrame( multi_indexed_data.flatten(), index=pd.MultiIndex.from_arrays(arrays_for_mi), columns=['value'] )[^2] print(df_with_multiindex.head()) ``` 通过这种方式构建起来的数据帧允许更加直观地查询和操作基于三个不同轴向坐标的元素集合。 这两种方案都有效地解决了如何把三维结构映射到二维表的问题;具体选择哪一种取决于实际应用场景和个人偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值