我需要拆分“国家/地区”列,因为该列在同一列中包含“索引和国家/地区名称”。但是,我收到一条错误消息。数据框:
df['country']
0 US
1 Spain
2 US
3 US
4 France
...
150925 Italy
150926 France
150927 Italy
150928 France
here is my codes:
# new data frame with split value columns
new = data["Name"].str.split(" ", n = 1, expand = True)
# making separate first name column from new data frame
data["id"]= new[0]
# making separate last name column from new data frame
data["Country"]= new[1]
# Dropping old Name columns
data.drop(columns =["country"], inplace = True)
# df display
data
我尝试使用字典,键值,但是没有成功。
-----------------------------------------------------------
df['country']
0 US
1 Spain
2 US
3 US
4 France
...
150925 Italy
150926 France
150927 Italy
150928 France
here is my codes:
# new data frame with split value columns
new = data["country"].str.split(" ", n = 1, expand = True)
# making separate first name column from new data frame
data["id"]= new[0]
# making separate last name column from new data frame
data["Country"]= new[1]
# Dropping old Name columns
data.drop(columns =["country"], inplace = True)
# df display
data
我想为ID和国家/地区分别设置一列:id国家0美国1西班牙2美国3美国4法国...150925意大利150926法国150927意大利150928法国150929意大利
您可以使用以下方法:
import pandas as pd
lst = ['US','Spain','US','France','Italy','France','Italy','France']
ids=list(range(len(lst)))
df = pd.DataFrame(lst)
newdf= pd.DataFrame(list(zip(ids,lst)),columns =['id', 'country'])
print (newdf)
我认为您有点困惑。在df['country']
,您会获得一个系列,系列总是与索引一起显示。如果要获取其值或索引,可以执行
df['country'].values
df['country'].index
希望这会有所帮助!
问题有点不清楚,所以我给出两个可能的建议:
1-如果您实际上有一个结合了数字和字符串值的列,则可以使用下面的代码将它们分成两个单独的列。
INPUT :
Name
0 France
1 India
2 US
3 Russia
CODE :
data[["ID","Country"]] = data["Name"].str.split(" ", n = 1, expand = True)
data=data.drop(["country"], axis=1)
2-如Alfonso所述,df [“ Country”]是一个序列,将与索引值一起显示。因此,可能会有些混乱。要求您确保事实并非如此。