使用Python将列中以逗号分隔的值分配到不同列中
在原始的数据表中,有一列叫做 'NVE Liste',而且这列只有一行。这个列里的值是一些用逗号分隔的数字,比如说:'0034104060001008405,00341040600001008498,00341040600002187444,00341040600002187505,00341040600002187512,00341040600002190079,00341040600002190093,00341040600002196880,00341040600012187434,00341040600012187496'。现在我想把每个用逗号分开的数字放到不同的列里。比如,第一个数字应该放在叫 'NVE1' 的列里,第二个数字放在 'NVE2' 的列里,依此类推,放到新的数据表中。
我该怎么做呢?任何帮助都非常感谢。
我试过用 str.split 方法,也尝试了其他不同的方法,但最后都没有成功,只是多了一列,里面的值还是一样的。
2 个回答
2
示例
import pandas as pd
df = pd.DataFrame(['001,002,003'], columns=['NVE Liste'])
数据框 df
NVE Liste
0 001,002,003
代码
使用 str.split
方法
out = (df['NVE Liste'].str.split(',', expand=True)
.rename(lambda x: f'NVE{x + 1}', axis=1)
)
输出结果:
NVE1 NVE2 NVE3
0 001 002 003
如果你想在 df
中创建一列,可以把 df
和 out
连接起来。
out2 = pd.concat([df, out], axis=1)
输出结果2
NVE Liste NVE1 NVE2 NVE3
0 001,002,003 001 002 003
0
你可以用和添加计算列一样的方法来做,但要用 str.split(',')。下面是一个可以用你提供的示例数据来实现的方式。
import pandas as pd
#Create a sample dataframe per the OP question
entrylist=[]
OriginalDF=pd.DataFrame(columns = [['NVEListe']])
#You can add more entries than just one to the list if you want a better example
entrylist.append('0034104060001008405,00341040600001008498,00341040600002187444,00341040600002187505,00341040600002187512,00341040600002190079,00341040600002190093,00341040600002196880,00341040600012187434,00341040600012187496')
OriginalDF.loc[0]=entrylist
print('This is the original DataFrame')
display(OriginalDF)
#split the original entry using the comma separator
splitentry=(OriginalDF.iloc[0]['NVEListe']).split(',')
#Make a list of names for the new columns
NewColumnlst=[]
for i in range(len(splitentry)):
NewColumnlst.append('NVEListe'+str(i+1))
#Split the string and add to new columns
for i in range(len(splitentry)):
OriginalDF[NewColumnlst[i]]=splitentry[i]
#Drop the unsplit original column
OriginalDF.drop('NVEListe', axis=1, inplace=True)
print('This is the new DataFrame showing the split columns')
display(OriginalDF)