python - 需要拆分具有混合数据的列

标签 python

我需要拆分“国家/地区”列,因为它在同一列中包含“索引和国家/地区名称”。但是,我收到一条错误消息。 数据框:

df['country']
0             US
1          Spain
2             US
3             US
4         France
           ...  
150925     Italy
150926    France
150927     Italy
150928    France

150929 意大利

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

150929 意大利

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)

关于python - 需要拆分具有混合数据的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404391/

相关文章:

python - TensorFlow 2.1 调用 cuInit : UNKNOWN ERROR (303) 失败

python - 需要在 python 脚本中运行 docker run 命令

python - 在情节图例中写 $\sqrt(2)$ 而不是 1.414

python - 用Python计算文件中奇数和偶数的总数

python - 删除 XML 中的重复节点

Python 任意数字转非科学字符串

python - FFT去除周期性噪声

python - sympy中函数的模块化逆

python - LSTM 不会过度拟合训练数据

python - 使用 scikit-learn 的 Web 应用程序