pandas python pandas没有连接到空的DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21196572/
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 21:35:01  来源:igfitidea点击:

python pandas not concat'ing into empty DataFrame

pythonpandasipython

提问by Chrispy

I'm iterating over a DataFrame, evaluating each row and then sticking it into another DataFrameby using the concat()method. However, the receiving DataFrameis still empty.

我正在迭代 a DataFrame,评估每一行,然后DataFrame使用该concat()方法将其粘贴到另一行中。然而,接收DataFrame仍然是空的。

import pandas as pd

empty = DataFrame(columns=('col1', 'col2'))

d = {'col1' : Series([1, 2, 3]),
    'col2' : Series([3, 4, 5])
}

some_data = DataFrame(d)

print empty
print some_data
print 'concat should happen below'

for index, row in some_data.iterrows():
    pd.concat([empty, DataFrame(row)])

print empty # should contain 3 rows of data

OUTPUT:

输出:

Empty DataFrame
Columns: [col1, col2]
Index: []
   col1  col2
0     1     3
1     2     4
2     3     5
concat should happen below
Empty DataFrame
Columns: [col1, col2]
Index: []

回答by Alvaro Fuentes

You need to update emptyif you want it to stores the values: empty = pd.concat([empty, DataFrame(row)])Also you can concatenate the whole DataFrames, try this print pd.concat([ empty,some_data])

empty如果您希望它存储值,则需要更新:empty = pd.concat([empty, DataFrame(row)])您也可以连接整个DataFrames,试试这个print pd.concat([ empty,some_data])

If you want to filter the rows you can try this:

如果你想过滤行,你可以试试这个:

def f(r):
    #check the row here
    return True #returns True or False if include/exclude the row

print some_data.groupby(some_data.index).filter(f)