Python 如何在不替换原始列的情况下将文本转换为列
我有一个只包含一列的文本文件,我想对该列执行文本到列操作,但不想替换原始列。只有在手动将文本文件中的第一列指定为“0”后,我才能对列执行文本转换,而不是使用原始列名“a、b、c、d、e、f、g、h、I、j、k、l、m、n、o、p、q、r、s、t、u、v、w、x、y、z”。我的代码如下:Python 如何在不替换原始列的情况下将文本转换为列,python,pandas,Python,Pandas,我有一个只包含一列的文本文件,我想对该列执行文本到列操作,但不想替换原始列。只有在手动将文本文件中的第一列指定为“0”后,我才能对列执行文本转换,而不是使用原始列名“a、b、c、d、e、f、g、h、I、j、k、l、m、n、o、p、q、r、s、t、u、v、w、x、y、z”。我的代码如下: import pandas as pd df=pd.read_csv("oss1.txt",sep='\t',engine='python') df['new']=df['0'].copy() def te
import pandas as pd
df=pd.read_csv("oss1.txt",sep='\t',engine='python')
df['new']=df['0'].copy()
def text_to_column(df, col):
df_detailed = df[col].str.rstrip(':| ').str.split(':| ', expand=True).astype(str)
#replace columns names if necessary
df_detailed.columns = df_detailed.columns.to_series().replace(":| ", ":| ")
#remove column and join new df
df_detailed = df.drop(col, axis=1).join(df_detailed)
return df_detailed
df = text_to_column(df,'new')
df.to_excel("output_oss1.xlsx", index = False)
i/p
o/p
- 列表项
df.str.split(",", expand=True)
df['new']=df['0'].copy()
?将'new'和'0'值分配给它工作的列之后。但是这个专栏的名字太大了,它不起作用。我无法解析这个问题。你想做什么?我想用I/P中给出的第一列的分隔符“”来做文本到列,但不想让列被替换为O/P/O,也许考虑不重写“代码> DF< /Cord>”,而是将信息存储在其他地方。
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z a b c d e f g h i j k l m n o p q r s t u v w x y z
apple, boy,cat,dog,egg,fish,girl,hen,ink,jug,kite,lion,man,net,owl,pen,queen,rat,seat,ten,umbrella,va,watch,xmas,yak,zebra apple boy cat dog egg fish girl hen ink jug kite lion man net owl pen queen rat seat ten umbrella van watch xmas yak zebra
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
df.str.split(",", expand=True)