Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拆分列并创建计算拆分值的新列_Python_Pandas - Fatal编程技术网

Python 拆分列并创建计算拆分值的新列

Python 拆分列并创建计算拆分值的新列,python,pandas,Python,Pandas,我有一个愚蠢的数据,其中一列包含多个用逗号拼凑在一起的值: [62]中的:df=pd.DataFrame({'U':['foo','bar','baz'],'V':['a,b,a,c,d','a,b,c','d,e']}) In[63]:df 出[63]: U V 0 foo a、b、a、c、d 1巴a、b、c 2巴兹d,e 现在我想拆分列V,删除它,然后通过e添加列a。a到e列应包含该行中该字母出现的次数: In [62]: df = pd.DataFrame({'U': ['foo', '

我有一个愚蠢的数据,其中一列包含多个用逗号拼凑在一起的值:

[62]中的
:df=pd.DataFrame({'U':['foo','bar','baz'],'V':['a,b,a,c,d','a,b,c','d,e']})
In[63]:df
出[63]:
U V
0 foo a、b、a、c、d
1巴a、b、c
2巴兹d,e
现在我想拆分列
V
,删除它,然后通过
e
添加列
a
a
e
列应包含该行中该字母出现的次数:

In [62]: df = pd.DataFrame({'U': ['foo', 'bar', 'baz'], 'V': ['a,b,a,c,d', 'a,b,c', 'd,e']})                                     

In [63]: df                                                                                                                      
Out[63]: 
     U  a  b  c  d  e
0  foo  2  1  1  1  0
1  bar  1  1  1  0  0
2  baz  0  0  0  1  1
也许是df['V'].str.split(',')和pandas.get_dummies的一些组合,但我不能完全理解


编辑:显然我必须证明为什么我的问题不是重复的。我认为,对于大多数不经意的观察者来说,原因是显而易见的。

这是
str.get\u dummies

pd.concat([df,df.pop('V').str.split(',',expand=True).stack().str.get_dummies().sum(level=0)],1)
Out[602]: 
     U  a  b  c  d  e
0  foo  2  1  1  1  0
1  bar  1  1  1  0  0
2  baz  0  0  0  1  1

您可以只使用
pandas.Series.str.count
。例如:

import pandas as pd

df = pd.DataFrame({'U': ['foo', 'bar', 'baz'], 'V': ['a,b,a,c,d', 'a,b,c', 'd,e']})

columns = ['a', 'b', 'c', 'd', 'e']
# If unknown or large set of columns, then replace above with:
# columns = sorted(set(df['V'].str.split(',').sum()))

for column in columns:
    df[column] = df['V'].str.count(column)

print(df)
#      U          V  a  b  c  d  e
# 0  foo  a,b,a,c,d  2  1  1  1  0
# 1  bar      a,b,c  1  1  1  0  0
# 2  baz        d,e  0  0  0  1  1

这个答案的可能重复再次表明了你对熊猫的深刻了解。回答得好!不能向上投票这一点,因为您可以在一行中添加一个
.drop(“V”,1)
,以精确匹配所需的输出。@pault使用pop:-)全部。哎哟仅当您知道中的可能值时才起作用advance@pault-你说得对。如果列值未知,则可以使用类似于排序(set(df['V'].str.split(',').sum())的结果替换for循环中的列表。我碰巧知道所有可能的值,但这似乎很乏味。不过,评论中的版本很好!