如何使用.loc在for循环中将数据帧行附加到另一行?

时间:2019-01-24 23:40:47

标签: python python-3.x pandas dataframe

假设我有以下数据框:

df_t1 = pd.DataFrame([["AAA", 1 ,2],["BBB", 0, 3],["CCC", 1, 2],["DDD", 0, 0],["EEE", 0, 3]], columns=list('ABC'))

    A   B   C
0   AAA 1   2
1   BBB 0   3
2   CCC 1   2
3   DDD 0   0
4   EEE 0   3

df_t2 = pd.DataFrame([["XXX", 4, 1],["YYY", 5 ,6],["ZZZ", 0, 3]], columns=list('ABC'))

    A   B   C
0   XXX 4   1
1   YYY 5   6
2   ZZZ 0   3

我可以使用以下代码在df_t1中找到满足特定条件的行:

df_t1.loc[(df_t1['B'] <= 2) & (df_t1['C'] > 2)]

A   B   C
1   BBB 0   3
4   EEE 0   3

df_t1.loc[(df_t1['B'] <= 3) & (df_t1['C'] > 3)]

    A   B   C
[Empty Dataframe]

我可以创建一个for循环,返回相同的结果:

for i in value_check:
    print(df_t1.loc[(df_t1['B'] <= i) & (df_t1['C'] > i)])

A  B  C
1  BBB  0  3
4  EEE  0  3
Empty DataFrame
Columns: [A, B, C]
Index: []

但是当我尝试使用该代码将这些值附加到df_t2时:

value_check = [2,3]

for i in value_check:
    df_t2.append(df_t1.loc[(df_t1['B'] <= i) & (df_t1['C'] > i)])

df_t2不变

2 个答案:

答案 0 :(得分:1)

从文档中添加方法:“将其他行追加到该帧的末尾,返回一个 new 对象”。您必须在循环中使用分配df_t2

value_check = [2,3]

for i in value_check:
    df_t2 = df_t2.append(df_t1.loc[(df_t1['B'] <= i) & (df_t1['C'] > i)])

也就是说,连接更为有效。

编辑:这是使用串联和列表理解的实现

df_t2 = pd.concat([df_t2] + [df_t1.loc[(df_t1['B'] <= i) & (df_t1['C'] > i)] for i in value_check], axis=0)

答案 1 :(得分:1)

使用pd.concat

df_t1 = pd.DataFrame([["AAA", 1 ,2],["BBB", 0, 3],["CCC", 1, 2],["DDD", 0, 0],["EEE", 0, 3]], columns=list('ABC'))

df_t2 = pd.DataFrame([["XXX", 4, 1],["YYY", 5 ,6],["ZZZ", 0, 3]], columns=list('ABC'))

value_check = [2, 3]

for i in value_check:
    condition = (df_t1['B'] <= i) & (df_t1['C'] > i)
    row_to_add = df_t1.loc[condition]

    df_t2 = pd.concat([df_t2, row_to_add], axis=0)