使用python将列中用逗号分隔的值分配给不同的列

问题描述 投票:0回答:2

在原始数据框中,有一列名为“NVE Liste”并且只有一行。该列中的值为 '0034104060001008405,00341040600001008498,00341040600002187444,00341040600002187505,00341040600002187512,003410406000021900 79,00341040600002190093,00341040600002196880,00341040600012187434,00341040600012187496'。现在首先我想将每个用逗号分隔的数字拆分到不同的列中。例如,在新数据框中,第一个数字应位于名为“NVE1”的列中,第二个数字应位于名为“NVE2”的列中,依此类推。

我怎样才能做到这一点,任何帮助将不胜感激

我尝试使用str.split,也尝试了不同的方法,但最终没有创建新的列,只是用相同的值创建了一个额外的列

python pandas excel pycharm
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']])
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)
© www.soinside.com 2019 - 2024. All rights reserved.