Python - 创建一个空的 Pandas DataFrame 并使用 For 循环从另一个 DataFrame 填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17001447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:53:49  来源:igfitidea点击:

Python - Create An Empty Pandas DataFrame and Populate From Another DataFrame Using a For Loop

python-2.7pandas

提问by DMML

Using: Python 2.7 and Pandas 0.11.0 on Mac OSX Lion

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

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

我正在尝试创建一个空的DataFrame,然后基于for loop.

I have found that when I construct the DataFrameand then use the for loopas follows:

我发现当我构造DataFrame然后使用for loop如下时:

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

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

结果为空DataFrame,但具有要从其他添加的相应列的标题DataFrame

回答by Andy Hayden

That's because you are using join incorrectly.

那是因为您错误地使用了 join。

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

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

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

回答by Greg Reda

What about just creating a new frame based off of the columns you know you want to keep, instead of creating an empty one first?

仅根据您知道要保留的列创建一个新框架,而不是先创建一个空的框架怎么样?

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':np.random.randn(5),
                    'b':np.random.randn(5),
                    'c':np.random.randn(5),
                    'd':np.random.randn(5)})
cols_to_keep = ['a', 'c', 'd']
dummies = ['d']
not_dummies = [x for x in cols_to_keep if x not in dummies]
data = df[not_dummies]
data

          a         c
0  2.288460  0.698057
1  0.097110 -0.110896
2  1.075598 -0.632659
3 -0.120013 -2.185709
4 -0.099343  1.627839