我有一个数据框,其中每个单元格中包含许多带有多个字符串的cloumns,我想获取字符串的子字符串,并将其作为新列添加到新数据框中,并在其中添加一个额外的列来描述第一列,例如下面的例子。我知道如何对原始数据帧中的一列执行此操作,但是我想一次对所有列执行此操作。
import pandas as pd
data = {'First': ['First string, second string, third string,...', 'NaN','First string, second string, third string,...'],
'Second': ['NaN', 'First string, second string, third string,...','First string, second string, third string,...'],
'third': ['First string, second string, third string,...', 'First string, second string, third string,...','NaN'],
'forth': ['First string, second string, third string,...', 'NaN','First string, second string, third string,...'],
....
}
df = pd.DataFrame (data, columns = ['First','Second',...])
一栏:
lst= df['first'].dropna().tolist()
my_list= [x for xs in lst for x in xs.split(',')]
df_new = pd.DataFrame(my_list, columns =['text'])
尽管我不确定如何添加第二个列,其大小与“ my_list”相同,并带有上一列的名称,所以在这种情况下为“第一列”。
所需的一列输出:
df_new:
text name
0 First string first
1 second string first
2 third string first
... ...
我想发生的是,来自df的所有列都作为行添加到df_new中,而“名称”列中的单元格具有与第一列字符串相对应的先前列的名称。
答案 0 :(得分:1)
我希望这会有所帮助!
#create the columns as rows
df_new = pd.DataFrame({'text':df.T.index})
df_new['text'] = df_new['text'].str.strip("'")
#create a new column for group
df_new['group']=1
#cumsum the column names
df_new['name'] = df_new.groupby('group')['text'].apply(lambda x: (x + ' ').cumsum().str.strip() + ",")
del df_new['group']