gpt4 book ai didi

python - 连接多个数据帧

转载 作者:行者123 更新时间:2023-12-01 08:53:55 24 4
gpt4 key购买 nike

我正在对给定的一组嵌套列表执行一些字符串操作,我只想在将这些列表连接到单个数据帧后创建一个 csv 。

我有一个类似的函数:

path = os.path.join(os.getcwd(),'C:\\.........')
files = [os.path.join(path,i) for i in os.listdir(path) if os.path.isfile(os.path.join(path,i))]

for file in files:

openfile = open(file,'r')
new_line = []

def separateState(l):
for line in l:
if any(x in line for x in ['NEW ENGLAND', 'MIDDLE ATLANTIC', 'E N CENTRAL', 'W N CENTRAL', 'SOUTH ATLANTIC', 'E S CENTRAL', 'W S CENTRAL', 'MOUNTAIN', 'PACIFIC']):
new_line.append(line.split())

separateState(openfile)

frames = list()

def join_words(n):
for listy in n:
grouper = groupby(listy, key=str.isalpha)
joins = [[' '.join(v)] if alpha_flag else list(v) for alpha_flag, v in grouper]
res = list(chain.from_iterable(joins))
df = pd.DataFrame(res)
frames.append(df)
df = pd.concat(frames)
df['Date'] = os.path.split(file)[-1]
df.to_csv('temp.csv', header = False)
print(frames)

join_words(new_line)

但这会为每个列表输出一个数据帧,因为它会覆盖之前的数据帧。

我如何操作它(我认为这是一个简单的修复),以便我从此函数获得单个数据帧和 CSV 文件输出?

最佳答案

考虑重构您的代码以提高组织和可读性,您似乎需要两个 pd.concat 调用:在新行级别和文本文件级别。

具体来说,请考虑以下因素:

  1. def 调用放置在带有 return 的任何循环之外。无需迭代地重新定义相同的函数。

  2. 读取文件时使用上下文管理器with,以避免处理后需要关闭。

  3. 让循环调用您的函数以返回输出,然后在末尾连接这些输出。

调整后的代码:

def separateState(txt):
new_line = []

with open(txt, 'r') as l:
for line in l:
if any(x in line for x in ['NEW ENGLAND', 'MIDDLE ATLANTIC',
'E N CENTRAL', 'W N CENTRAL',
'SOUTH ATLANTIC', 'E S CENTRAL',
'W S CENTRAL', 'MOUNTAIN', 'PACIFIC']):
new_line.append(line.split())

return new_line

def join_words(n, txt):
frames = list()

for listy in n:
grouper = groupby(listy, key=str.isalpha)
joins = [[' '.join(v)] if alpha_flag else list(v) for alpha_flag, v in grouper]
res = list(chain.from_iterable(joins))
df = pd.DataFrame(res)
df['Date'] = os.path.split(txt)[-1]
frames.append(df)

new_df = pd.concat(frames)
return new_df


df_list = []
for file in files:
new_line = separateState(file)
df = join_words(new_line, file)
df_list.append(df)

final_df = pd.concat(df_list)
final_df.to_csv('temp.csv', header = False)
print(df_list)

关于python - 连接多个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com