Skip to main content
 首页 » 编程设计

python之删除单引号和分隔括号

2025年05月04日22sky-heaven

我是 Python 的新手,正在研究数据集。我需要帮助来尝试: 1.去掉括号内日期的单引号 2.将括号拆分成数组(31312 x 4)

代码: 导入 csv 将 numpy 导入为 np 将 pandas 导入为 pd

text_file = open("Claims1.txt", "r") 
dfl = DataFrameList = list(text_file) 
text_file.close() 
 
 
dfl_string = "\n".join(str(e) for e in dfl) 
dfl_split = dfl_string.replace('),', ')//').split('//') 
 
 
my_df = pd.DataFrame(dfl_split) 
#Output into CSV file 
my_df.to_csv('output.csv') 
 
 
 
Current Result: 
     0 
0   (1,'2000-01-04',328647,5000) 
1   (2,'2000-01-09',465858,5000) 
2   (3,'2000-01-09',378115,5000) 
3   (4,'2000-01-14',121895,5000) 
4   (5,'2000-01-16',325172,5000) 
5   (6,'2000-01-16',156062,5000) 
6   (7,'2000-01-17',472142,5000) 
............................... 
31312 (31312, '2004-05-30',340406, 5000) 
 
Desired Result: 
    0       1         2      3 
0   1  2000-01-04  328647  5000 
1   2  2000-01-09  465858  5000 
2   3  2000-01-09  378115  5000 
3   4  2000-01-14  121895  5000 
4   5  2000-01-16  325172  5000 
5   6  2000-01-16  156062  5000 
6   7  2000-01-17  472142  5000 
.............................. 
31312 31312 '2004-05-30'340406 5000 

请您参考如下方法:

假设您的数据位于数据框中,您可以使用 pd.Series.apply 拆分成列:

import pandas as pd 
 
df = pd.DataFrame({0:[(1,'2000-01-04',328647,5000), 
                      (2,'2000-01-09',465858,5000), 
                      (3,'2000-01-09',378115,5000), 
                      (4,'2000-01-14',121895,5000), 
                      (5,'2000-01-16',325172,5000), 
                      (6,'2000-01-16',156062,5000), 
                      (7,'2000-01-17',472142,5000)]}) 
 
df[[0, 1, 2, 3]] = df[0].apply(pd.Series) 
 
#    0           1       2     3 
# 0  1  2000-01-04  328647  5000 
# 1  2  2000-01-09  465858  5000 
# 2  3  2000-01-09  378115  5000 
# 3  4  2000-01-14  121895  5000 
# 4  5  2000-01-16  325172  5000 
# 5  6  2000-01-16  156062  5000 
# 6  7  2000-01-17  472142  5000