何时使用拆分和结构拆分()Pandas系列?

2024-04-26 22:12:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道为什么我们不能用split代替结构拆分在下面的代码和创建“ID”变量时,为什么使用了两次“.str”

import pandas as pd

df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
    if col[:2]=='01':
    df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
    df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
    df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
    df.rename(columns={col:'#'+col[1:]}, inplace=True)

names_ids = df.index.str.split('\s\(') 
df.index = names_ids.str[0] # the [0] element is the country name (new index) 
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or 
                       #ID (take first 3 characters from that)

.str转换为字符串,在创建“ID”变量时使用它的目的是什么? .分裂和分裂有什么区别 str.split公司?你知道吗


Tags: columnstheidtrueidsdfindexif