如何通过python代码将csv中的ID号从A列分离到B列?

2024-09-26 17:48:16 发布

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

所以基本上我被卡住了,因为我尝试了这段代码,但它并没有把名字和号码分开。请参考样本图片以了解预期结果

我试过的代码

编辑2: 名称\u tab2文件链接

https://wetransfer.com/downloads/349f20af819edf2702b27ac6e0c9c22b20211019083824/e09ef6


Tags: 文件代码https名称com编辑链接downloads
2条回答

您在引用和分隔符方面有问题。要清除数据帧,请使用以下代码:

pd.read_csv('names_tab2.csv', quoting=1, header=None)[0] \
  .str.split('\t', expand=True) \
  .to_csv('clean_names.csv', index=False, header=False)

旧答案 使用str.extract

假设此数据帧:

df = pd.DataFrame({'ColA': ['CAIN TAN86092142', 'YEO KIAT JUN81901613']})
print(df)

# Output:
                   ColA
0      CAIN TAN86092142
1  YEO KIAT JUN81901613

在遇到的第一个数字上拆分:

out = df['ColA'].str.extract(r'([^\d]*)(\d+)') \
                .rename(columns={0: 'Name', 1: 'Number'})
print(out)

# Output:
           Name    Number
0      CAIN TAN  86092142
1  YEO KIAT JUN  81901613

更新

Is there a way to remove the Name and Number when it outputs to the csv?

out.to_csv('data.csv', index=False, header=None)

# content of data.csv:
CAIN TAN,86092142
YEO KIAT JUN,81901613

当打开纯文本文件(或者在本例中是纯文本csv文件)时,可以使用for循环逐行遍历文件,就像这样(从Python 3开始,当前为):

name = []
id_num = []

file = open('file.csv', 'r')

for f in file:
    f = f.split(',')               # split the data
    name.append(str(f[0]))     # append name to list
    id_num.append(str(f[1]))   # append ID to list
    

既然列表中有了数据,您就可以按自己的方式打印/存储它了

相关问题 更多 >

    热门问题