Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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如何提取dataframe中[]括号内的指定字符串,并使用布尔值创建新列_Python_String_Python 2.7_Pandas_Extraction - Fatal编程技术网

Python如何提取dataframe中[]括号内的指定字符串,并使用布尔值创建新列

Python如何提取dataframe中[]括号内的指定字符串,并使用布尔值创建新列,python,string,python-2.7,pandas,extraction,Python,String,Python 2.7,Pandas,Extraction,我是编程新手,非常感谢您的任何见解 我有一个这样的数据框 df 我想根据信息列中的信息创建具有活动名称的新列,如果信息列中有相应名称,则在新列中添加1。它将看起来像下面的dataframe Price Sailing Boating Surfing 0 $100 1 0 0 1 $200 1 1 0 2 $300 0 0 1 我尝试了一次代码攻击

我是编程新手,非常感谢您的任何见解

我有一个这样的数据框

df

我想根据信息列中的信息创建具有活动名称的新列,如果信息列中有相应名称,则在新列中添加1。它将看起来像下面的dataframe

   Price  Sailing  Boating  Surfing
0   $100       1         0        0
1   $200       1         1        0
2   $300       0         0        1
我尝试了一次代码攻击,但没有成功…(尽管这种方法在其他专栏中也有效)


我有超过10000个这样的数据,所以理想情况下,我想写一个代码,自动提取信息列中的指定字符串(如冲浪),创建一个带有活动名称的新列,并返回1或0,如上所示。我认为数据框中的数据或数据类型中的括号可能会导致问题,但我不确定如何解决这个问题。

我假设info列中的值的格式类似于Python列表

df1 = df['info'].str[1:-1].str.replace(' ', '').str.get_dummies(',')
df1.rename(columns=lambda x: x.rsplit(':')[-1], inplace=True)
df2 = pd.concat([df, df1.astype(int)], axis=1)

df2
Out: 
                         info Price  Sailing  Boating  Surfing
0               [100:Sailing]  $100        1        0        0
1  [150:Boating, 100:Sailing]  $200        1        1        0
2               [200:Surfing]  $300        0        0        1

谢谢你的建议!我想不出这种方法;)在运行代码时,我遇到了这样一个错误:“AttributeError:只能使用字符串值的.str访问器,它在pandas中使用np.object dtype”。这个错误听起来像是info列中的值不是字符串值,我需要以某种方式更改它以运行代码..(?)你知道是什么导致了这个错误吗?我认为它们可能是实际的列表。你能试着把它作为第一行吗!它就像一个魔术!非常感谢你!我意识到
df['info'].str.join(“'uuuuuu')
神奇地删除了info列中的括号。但我还没有弄清楚整个逻辑是如何运作的。你能详细说明一下
.str.join(“\uuuuu”)
.str.get\u假人(“\uuuuuuu”)
的作用吗?我真的很想理解这一点。实际上没有括号。只有在打印列表时才能看到这些括号
str.join(sep)
获取列表中的每个元素,并使用提供的分隔符将它们连接起来。因此,如果您有一个列表
['a'
,'b','c']`,str.join(',')将为您提供'a,b,c'。由于str.get_dummies使用分隔符生成列,因此该分隔符应该是在实际字符串中看不到的。如果确定文本中没有逗号,也可以使用逗号(用于连接和获取虚拟对象)。
df1 = df.info.str.extract(r'(Boating|Sailing|Surfing)',expand=False)
df2 = pd.concat([df,pd.get_dummies(df1).astype(int)],axis=1)
df1 = df['info'].str[1:-1].str.replace(' ', '').str.get_dummies(',')
df1.rename(columns=lambda x: x.rsplit(':')[-1], inplace=True)
df2 = pd.concat([df, df1.astype(int)], axis=1)

df2
Out: 
                         info Price  Sailing  Boating  Surfing
0               [100:Sailing]  $100        1        0        0
1  [150:Boating, 100:Sailing]  $200        1        1        0
2               [200:Surfing]  $300        0        0        1