【问题标题】:Pandas: convert object to str熊猫:将对象转换为str
【发布时间】:2021-12-05 12:56:31
【问题描述】:

我有以下数据框:

    R_fighter       B_fighter           win_by                  last_round  Referee         date            Winner
0   Adrian Yanez    Gustavo Lopez       KO/TKO                  3           Chris Tognoni   March 20, 2021  Adrian Yanez
1   Trevin Giles    Roman Dolidze       Decision - Unanimous    3           Herb Dean       March 20, 2021  Trevin Giles
2   Tai Tuivasa     Harry Hunsucker     KO/TKO                  1           Herb Dean       March 20, 2021  Tai Tuivasa
3   Cheyanne Buys   Montserrat Conejo   Decision - Unanimous    3           Mark Smith      March 20, 2021  Montserrat Conejo
4   Marion Reneau   Macy Chiasson       Decision - Unanimous    3           Mark Smith      March 20, 2021  Macy Chiasson

我正在尝试将列 win_by 的类型从 object 转换为 str
我按照这里的建议使用.astype() How to convert column with dtype as object to string in Pandas Dataframe

UFC_db['win_by'] = UFC_db['win_by'].astype('|S')

但没有任何改变:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6012 entries, 0 to 6011
Data columns (total 7 columns):
 #   Column      Non-Null Count  Dtype 
---  ------      --------------  ----- 
 0   R_fighter   6012 non-null   object
 1   B_fighter   6012 non-null   object
 2   win_by      6012 non-null   object
 3   last_round  6012 non-null   object
 4   Referee     6012 non-null   object
 5   date        6012 non-null   object
 6   Winner      6012 non-null   object
dtypes: object(7)
memory usage: 328.9+ KB

我也试过

UFC_db['win_by'] = UFC_db['win_by'].astype('str')

UFC_db['win_by'] = UFC_db['win_by'].astype(str)

UFC_db['win_by'] = UFC_db['win_by'].astype('str',errors ="ignore")

这里建议Python - pandas column type casting with "astype" is not working

但仍然没有任何改变

【问题讨论】:

  • 你试过UFC_db['win_by'] = UFC_db['win_by'].astype("|S")
  • 是的 CaseyKnight,这是我的第一次尝试!

标签: pandas string object types


【解决方案1】:

我意识到object 不是问题,而是 pandas 用于字符串或混合类型的类型 (https://pbpython.com/pandas_dtypes.html)。更准确地说:

Pandas dtype Python type NumPy type Usage
object str or mixed string_, unicode_, mixed types Text or mixed numeric and non-numeric values
int64 int int_, int8, int16, int32, int64, uint8, uint16, uint32, uint64 Integer numbers
float64 float float_, float16, float32, float64 Floating point numbers

事实上,如果我打印单个单元格的类型,它会给我str

type(UFC_db.at[0,'Referee'])

str

作为一个字符串,我可以用另一个字符串来改变它

UFC_db.at[0,'Referee'] = 'XXXXXX'
UFC_db.at[0,'Referee']

'XXXXXX'

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2022-06-22
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多