Python - 创建一个空的 Pandas DataFrame 并使用 For 循环从另一个 DataFrame 填充 [英] Python - Create An Empty Pandas DataFrame and Populate From Another DataFrame Using a For Loop

查看:133
本文介绍了Python - 创建一个空的 Pandas DataFrame 并使用 For 循环从另一个 DataFrame 填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:Mac OSX Lion 上的 Python 2.7 和 Pandas 0.11.0

Using: Python 2.7 and Pandas 0.11.0 on Mac OSX Lion

我正在尝试创建一个空的 DataFrame,然后基于 for 循环 从另一个数据帧填充它.

I'm trying to create an empty DataFrame and then populate it from another dataframe, based on a for loop.

我发现当我构造DataFrame然后使用for循环如下:

I have found that when I construct the DataFrame and then use the for loop as follows:

data = pd.DataFrame()
for item in cols_to_keep:
    if item not in dummies:
        data = data.join(df[item])

结果是一个空的 DataFrame,但带有要从另一个 DataFrame 添加的相应列的标题.

Results in an empty DataFrame, but with the headers of the appropriate columns to be added from the other DataFrame.

推荐答案

那是因为你使用的连接不正确.

That's because you are using join incorrectly.

您可以使用列表理解将 DataFrame 限制为您想要的列:

You can use a list comprehension to restrict the DataFrame to the columns you want:

df[[col for col in cols_to_keep if col not in dummies]]

这篇关于Python - 创建一个空的 Pandas DataFrame 并使用 For 循环从另一个 DataFrame 填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆