Python pandas读取.txt文件,导出.csv文件,并使用分隔列



我有一个问题,我试图读取一个。txt文件并导出到。csv,并使用分隔符按列使用类别分隔行。

file.txt是这样的

[groups] 
admins = user1,user2,user3 
users_network = user4,user5 
users_m4s = user6,user7,user8,user9 

.csv文件应该是

groups
user1 = admins
user2 = admins
user3 = admins
user4 = users_network
user5 = users_network
user6 = users_m4s ... for the rest of element of category line

我试着

import pandas as pd
import numpy as np
df = pd.read_table("D:GIT-filesAutomate-StatsSVN_sample_filessample_svn_input.txt" , sep='=',engine='python')
print(df)
df.to_csv("D:GIT-filesAutomate-StatsSVN_sample_filessample_svn_input_update.csv" , index=None)
df = pd.read_table ("D:GIT-filesAutomate-StatsSVN_sample_filessample_svn_input_update.csv" , sep='=',engine='python')
print(df)

但它没有创建正确的。csv和显示

我能够根据提供的代码获得所需的结果,使用这行代码

df = pd.read_csv(r"D:GIT-filesAutomate-StatsSVN_sample_filessample_svn_input.txt", sep = '|')
df.columns = ['groups']
df['New Columns'] = df['groups'].apply(lambda x : x.split('=')[0])
df['groups'] = df['groups'].apply(lambda x : ' '.join(x.split('=')[1:]))
df['groups'] = df['groups'].apply(lambda x : x.split(','))
df = df.explode('groups')
df['groups'] = df['New Columns'] + ' = ' + df['groups']
df = df[['groups']]
df.to_csv("D:GIT-filesAutomate-StatsSVN_sample_filessample_svn_input_update.csv" , index = False)

相关内容

  • 没有找到相关文章

最新更新