我有一个SQL查询的以下DataFrame:
(Pdb) pp total_rows
ColumnID RespondentCount
0 -1 2
1 3030096843 1
2 3030096845 1
Run Code Online (Sandbox Code Playgroud)
我想像这样转动它:
total_data = total_rows.pivot_table(cols=['ColumnID'])
(Pdb) pp total_data
ColumnID -1 3030096843 3030096845
RespondentCount 2 1 1
[1 rows x 3 columns]
total_rows.pivot_table(cols=['ColumnID']).to_dict('records')[0]
{3030096843: 1, 3030096845: 1, -1: 2}
Run Code Online (Sandbox Code Playgroud)
但我想确保将303列作为字符串而不是整数进行转换,以便我得到:
{'3030096843': 1, '3030096845': 1, -1: 2}
Run Code Online (Sandbox Code Playgroud) 为什么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,这是正确的. …
我在pandas中有一个数据帧,我正在试图弄清楚它的值是什么类型.我不确定列的类型是什么'Test'.但是,当我跑步时myFrame['Test'].dtype,我得到;
dtype('O')
Run Code Online (Sandbox Code Playgroud)
这是什么意思?
我想在一个pandas数据帧的所述列中的每个值的开头附加一个字符串(优雅地).我已经想出了如何做到这一点,我目前正在使用:
df.ix[(df['col'] != False), 'col'] = 'str'+df[(df['col'] != False), 'col']
Run Code Online (Sandbox Code Playgroud)
这似乎是一件不公平的事情 - 你知道其他任何方式(也许这个特性也可以将字符添加到该列为0或NaN的行中)吗?
如果还不清楚,我想转向:
col
1 a
2 0
Run Code Online (Sandbox Code Playgroud)
成:
col
1 stra
2 str0
Run Code Online (Sandbox Code Playgroud)