相关疑难解决方法(0)

在Pandas中将列转换为字符串

我有一个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)

python numpy pandas

130
推荐指数
6
解决办法
34万
查看次数

DataFrame中的字符串,但dtype是对象

为什么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,这是正确的. …

python types numpy series pandas

86
推荐指数
4
解决办法
4万
查看次数

标签 统计

numpy ×2

pandas ×2

python ×2

series ×1

types ×1