我正在尝试从两个现有框架的列创建一个新的 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
最佳答案
这是因为:
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
然后你会得到一个带有 'value' 列的 df
双 [[]]
强制返回一个 df,因为它将传入的参数解释为一个列列表(只有 1 个条目),而不是将返回一个列标签Series
这是设计的
你可以在这里看到区别:
In [202]:
print(type(df1['value']))
print(type(df1[['value']]))
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
您的其余代码失败,因为该对象的类型为 Series
并且 Series
具有 columns
属性毫无意义或允许重命名列。
关于pandas.concat 忘记列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648733/