pandas.concat 忘记列名

Aar*_*lla 1 merge dataframe pandas

我正在尝试DataFrame从两个现有框架的列创建一个新的,但在 之后concat(),列名丢失,我无法分配新的:

import pandas
import datetime

dt = datetime.datetime

df1 = pandas.DataFrame({'value': [1.1, 2.1], 'foo': ['a', 'b']}, index=[dt(2015, 11, 1), dt(2015, 11, 2)])
df2 = pandas.DataFrame({'value': [1.2, 2.2]}, index=[dt(2015, 11, 3), dt(2015, 11, 4)])

# Keeps 'foo'
df = pandas.concat([df1, df2])
print df
print

# Without foo but column names are also lost
# plus there is an additional odd line "Name: value, dtype: float64"
df = pandas.concat([df1['value'], df2['value']])
print df
print

# AttributeError: 'Series' object has no attribute 'columns'
print repr(df.columns)
# no effect (probably because this isn't a supported attribute)
df.columns = ['value']
print df

# Fails: rename() got an unexpected keyword argument "columns"
df.rename(columns={'': 'value'}, inplace=True)
print df
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2
Run Code Online (Sandbox Code Playgroud)

我想要的输出:

            value
2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 5

这是因为:

df = pandas.concat([df1['value'], df2['value']])
Run Code Online (Sandbox Code Playgroud)

连接 2 个Series对象而不是 dfs,

如果你这样做:

In [201]:
df = pd.concat([df1[['value']], df2[['value']]])
df

Out[201]:
            value
2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2
Run Code Online (Sandbox Code Playgroud)

然后你会得到一个带有“值”列的 df

double[[]]强制返回 df,因为它将传入的 param 解释为 cols 列表(只有 1 个条目)而不是列标签,后者将返回Series设计为

你可以在这里看到不同之处:

In [202]:
print(type(df1['value']))
print(type(df1[['value']]))

<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
Run Code Online (Sandbox Code Playgroud)

其余代码失败,因为该对象属于类型,Series并且 aSeries具有columns属性或允许重命名列是没有意义的。