我正在尝试从两个现有框架的列创建一个新的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
我得到的输出:
2015-11-01 1.1
2015-11-02 2.1
2015-11-03 1.2
2015-11-04 2.2
我想要的输出:
value
2015-11-01 1.1
2015-11-02 2.1
2015-11-03 1.2
2015-11-04 2.2
答案 0 :(得分:3)
这是因为:
df = pandas.concat([df1['value'], df2['value']])
连接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
然后你得到一个带有'值的df'柱
double [[]]
强制返回一个df,因为它将传入的param解释为cols列表(只有一个条目),而不是一个将返回Series
的列标签是设计
你可以在这里看到差异:
In [202]:
print(type(df1['value']))
print(type(df1[['value']]))
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
其余代码失败,因为该对象属于Series
类型,Series
具有columns
属性或允许重命名列无效。
答案 1 :(得分:0)
我发现最好这样做。
new_df = pd.concat([my_df1, my_df2.rename('Name')], axis = 1)