为什么Pandas告诉我我有对象,尽管所选列中的每个项都是一个字符串 - 即使在显式转换之后也是如此.
这是我的DataFrame:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 56992 entries, 0 to 56991
Data columns (total 7 columns):
id 56992 non-null values
attr1 56992 non-null values
attr2 56992 non-null values
attr3 56992 non-null values
attr4 56992 non-null values
attr5 56992 non-null values
attr6 56992 non-null values
dtypes: int64(2), object(5)
Run Code Online (Sandbox Code Playgroud)
其中五个是dtype object.我明确地将这些对象转换为字符串:
for c in df.columns:
if df[c].dtype == object:
print "convert ", df[c].name, " to string"
df[c] = df[c].astype(str)
Run Code Online (Sandbox Code Playgroud)
然后,df["attr2"]仍然有dtype object,虽然type(df["attr2"].ix[0]揭示str,这是正确的. …
考虑以下数据帧(注意字符串):
df = pd.DataFrame([['3', '11'], ['0', '2']], columns=list('AB'))
df
Run Code Online (Sandbox Code Playgroud)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 2 columns):
A 2 non-null object
B 2 non-null object
dtypes: object(2)
memory usage: 104.0+ bytes
Run Code Online (Sandbox Code Playgroud)
我要总结一下.我希望字符串能够连接起来.
df.sum()
A 30.0
B 112.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)
看起来字符串连接然后转换为float.有这么好的理由吗?这是一个错误吗?任何有启发性的东西都会被投票.
在回答这个问题时,我发现在使用meltpandas数据帧之后,以前是有序分类dtype的列变为了object.这是预期的行为吗?
注意:不寻找解决方案,只是想知道这种行为是否有任何原因,或者它是否不是预期的行为.
例:
使用以下数据框df:
Cat L_1 L_2 L_3
0 A 1 2 3
1 B 4 5 6
2 C 7 8 9
df['Cat'] = pd.Categorical(df['Cat'], categories = ['C','A','B'], ordered=True)
# As you can see `Cat` is a category
>>> df.dtypes
Cat category
L_1 int64
L_2 int64
L_3 int64
dtype: object
melted = df.melt('Cat')
>>> melted
Cat variable value
0 A L_1 1
1 B L_1 4
2 C L_1 7
3 …Run Code Online (Sandbox Code Playgroud)