python是否可以从现有数据框创建新数据框?

时间:2018-11-23 05:12:47

标签: python pandas

我想问一下这个问题,因为我创建了这样的代码,但是它只返回了标头。

以下是我的df名称df_all的示例

Doc       name count year
[A1,A2]   John   1   2018
[A1,A3]   Mark   0   2018
[A2,A4]   John   3   2018

这是我尝试过的代码

n_wsp_71 = [i for i in df_all if i.count != 0]
n_wsp_71

这是我的结果

['Doc', 'name', 'count', 'year']

但是我希望看到这个结果

newdf
        Doc       name count year
        [A1,A2]   John   1   2018
        [A2,A4]   John   3   2018

2 个答案:

答案 0 :(得分:2)

df = pd.DataFrame({"Doc": [["A1","A2"], ["A1","A3"], ["A2","A4"]], "name": ["John", "Mark", "John"], "count": [1,0,3], "year": [2018, 2018, 2018]})

df2 = df.query("count!=0").reset_index(drop=True)

# for count = 0
df2 = df.query("count==0").reset_index(drop=True)

#method 2
df2 = df[~(df["count"].isin(['0']))].reset_index(drop=True)

# for count = 0
df2 = df[(df["count"].isin(['0']))].reset_index(drop=True)
print(df2)

输出:

        Doc  name  count  year
0  [A1, A2]  John      1  2018
1  [A2, A4]  John      3  2018

        Doc  name  count  year
0  [A1, A3]  Mark      0  2018

答案 1 :(得分:1)

您正在对熊猫数据框进行列表理解,这将永远无法工作

所以您必须这样做:

list_all=list_all[list_all['count']!=0]

现在:

print(list_all)

是:

Doc       name count year
[A1,A2]   John   1   2018
[A2,A4]   John   3   2018
相关问题