【问题标题】:Cut down the length of array based on its index in a column根据列中的索引减少数组的长度
【发布时间】:2021-01-09 09:47:30
【问题描述】:

我有一个类似这样的数据框:

    signal
0   0.469112    -0.282863 -1.509059 -1.135632   1.212112    -0.173215   0.119209  -1.044236 
1   0.469152    0.32863    1.509059  1.135632   1.212112     0.173215   0.419209  -1.044236 
2   0.469152    0.32843    1.209059  5.135632   6.212112    -0.173215   -0.419209 -7.044236 

预期输出:

 signal
0    -1.509059  -1.135632   1.212112    -0.173215   0.119209        
1    1.509059    1.135632   1.212112     0.173215   0.419209        
2    1.209059    5.135632   6.212112    -0.173215   -0.419209   

我想遍历列“信号”(数组)并选择输入在每行第三和第五之间的数据。在真实数据集中,每行信号的长度从 10 到 8000 不等。我尝试了类似 df.signal.iloc[3:5] 的方法,但它不起作用。那我该怎么做。谢谢!

【问题讨论】:

    标签: python arrays pandas dataframe


    【解决方案1】:

    IIUC 你需要str索引:

    df.signal.str[2:7]
    

    Pandas 从0 计数,因此对于从3.6. 列的选择,请使用:

    df1 = df.signal.str[2:6]
    print (df1)
    0    [-1.509059, -1.135632, 1.212112, -0.173215]
    1       [1.509059, 1.135632, 1.212112, 0.173215]
    2      [1.209059, 5.135632, 6.212112, -0.173215]
    Name: signal, dtype: object
    

    【讨论】:

    • @jezrale 谢谢!我试图像这样应用到数据框中的整个列:df.singal.apply(lambda x : x.str[300:1300]) 并得到了这个 AttributeError: 'numpy.ndarray' object has no attribute 'str'
    • @almo - 为什么是apply?使用df.singal.str[300:1300]
    猜你喜欢
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多