查看 (5946)
我从SQL查询中获得了以下DataFrame:
(Pdb) pp total_rows ColumnID RespondentCount 0 -1 2 1 3030096843 1 2 3030096845 1
我想把它像这样:
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}
但是,我希望确保303列被转换为字符串而不是整数,这样我就可以得到以下内容:
写回答邀请回答
提问于

2 个回答

转换为字符串的一种方法是使用astype:
total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)
转换为字符串的一种方法是使用astype: total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)
用户回答回答于
对于将多个列转换为字符串而不是单个列特别有用:
In [76]: import numpy as np In [77]: import pandas as pd In [78]: df = pd.DataFrame({ ...: 'A': [20, 30.0, np.nan], ...: 'B': ["a45a", "a3", "b1"], ...: 'C': [10, 5, np.nan]}) ...: In [79]: df.dtypes ## Current datatype Out[79]: A float64 B object C float64 dtype: object ## Multiple columns string conversion In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) In [81]: df.dtypes ## Updated datatype after string conversion Out[81]: A object B object C object dtype: object
对于将多个列转换为字符串而不是单个列特别有用: In [76]: import numpy as np In [77]: import pandas as pd In [78]: df = pd.DataFrame({ ...: 'A': [20, 30.0, ...

所属标签