我有一个像这样的Pandas DataFrame(摘自官方教程):
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
DF = pd.DataFrame(d)
我想添加一个列表(或元组)作为DataFrame属性
DF.Attribute = ['Some random','infos in','a list']
它过去工作正常,但由于我最近更新了Pandas(版本0.21.0),我收到此警告:
UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access
DF.Attribute = ['Some random','infos in','a list']
你知道如何避免这种警告吗?
答案 0 :(得分:-1)
使用[]
,但因为df
长度越少Series
需要按length
过滤L = ['Some random','infos in','a list']
DF['Attribute'] = pd.Series(L, index=DF.index[:len(L)])
print (DF)
one two Attribute
a 1.0 1.0 Some random
b 2.0 2.0 infos in
c 3.0 3.0 a list
d NaN 4.0 NaN
:
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
DF = pd.DataFrame(d)
DF.columns.name = "The title of my DataFrame"
print (DF)
The title of my DataFrame one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
print (DF.columns.name)
The title of my DataFrame
编辑:
DF.columns.name = None
print (DF)
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
删除它:
DF = DF.rename_axis("The title of my DataFrame", axis=1)
print (DF)
The title of my DataFrame one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
替代set_index
:
A = 10,
A(minus) = 9,
B = 8,
B(minus) = 7,
C = 6,
C(minus) = 5