如何使用pandas从csv获取所有列值

时间:2017-12-06 05:35:01

标签: python pandas csv

我在.csv中有一个包含一些随机消息的表:

Last Tweet @ 2017-12-02 13:52:36 ...fetching more
2017-12-01 21:06:35
2017-12-01 12:29:27
2017-12-01 12:27:36

我想只获得符合特定条件的行。我设法做到了,但我希望获得列的所有单元格值 - 符合条件的msg。

我的代码:

id,msg
2,start
1,bot
1,run
2,san

当我df = pd.read_csv('msgs.csv') # if id==2 and msg contains letter 'a' p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))] print(p) for row in p: print(p.iloc[0]['msg']) 我的结果(这是好的)是:

print(p)

我希望得到这样的输出:

           id msg
1          2  start
5          2    san

但是当我尝试使用start san 时,我只得到第一个单元格值:

iloc

可能解决方案很简单,但我不知道如何获得它。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以随时执行此操作:

for x in p['msg'].values:
    print(x)

答案 1 :(得分:0)

您可以像这样迭代csv中的每一行:

function divideEqually(h1, h2, diff) {
    let threshold = 40;
    let diffSplit = diff / 2;
    let leftOut1 = 0,
        leftOut2 = 0,
        leftOut = 0;

    if (h1 != threshold) {
        h1 = h1 + diffSplit;
    } else {
        leftOut1 = diffSplit;
    }
    if (h2 != threshold) {
        h2 = h2 + diffSplit;
    } else {
        leftOut2 = diffSplit;
    }

    diff = 0;
    if (h1 < threshold) {
        leftOut1 = threshold - h1;
        h1 = threshold;
    }
    if (h2 < threshold) {
        leftOut2 = threshold - h2;
        h2 = threshold;
    }

    diff = Math.ceil(leftOut1 + leftOut2);
    // error margin
    if (Math.abs(diff) > 0.5) {
        return divideEqually(h1, h2, diff);
    }
    return {
        h1: h1,
        h2: h2
    };
}

const qs = handle => document.querySelector(handle)
let initialHeight = window.innerHeight;

window.addEventListener('resize',()=>{
    const newHeight = window.innerHeight;
    const changeInHeight = newHeight - initialHeight;

    const h1 = qs("#top");
    const h2 = qs("#bottom")
    const h = divideEqually(h1.clientHeight,h2.clientHeight,changeInHeight);
    initialHeight = newHeight;

    h1.style.height = h.h1 + "px";
    h2.style.height = h.h2 + "px";

    // debug
    h1.innerHTML = h.h1;
    h2.innerHTML = h.h2;
})

这将得到以下结果:

for row_number,id,msg in p:
    print(row-number,id,msg)

因此,如果您只想要'msg',请打印:

1 2  start
5 2  san

希望这有帮助!