简体   繁体   English

从一列的值向DataFrame添加新列

[英]Add new columns to DataFrame from the value of one column

I have a pandas DataFrame, there is a column with values like a,b,c ie string splited by ','. 我有一个熊猫DataFrame,有一列的值,如a,b,c,即用','分割的字符串。 Now I want to create new columns, for example, for a,b,c there would be new column a, column b, column c. 现在,我想创建新列,例如,对于a,b,c,将有新列a,b列,c列。 then the data with a,b,c would get a value of true on the three columns, the data with a,b,e would get true on columns a and b but false on c, maybe it is more clearly to see the picture below. 那么a,b,c的数据在三列中的值为true,a,b,e的数据在a和b列中的值为true,而c的值为false,也许更清楚地看到图片下面。 How to do this? 这个怎么做?

在此处输入图片说明

Use str.get_dummies with cast to bool by astype and add column B by join : 使用str.get_dummiesstr.get_dummies按类型astype为bool并通过join添加B列:

df1 = df['A'].str.get_dummies(',').astype(bool).join(df['B'])
print (df1)
       a     b     c      f  B
0   True  True  True  False  3
1  False  True  True   True  4

More general solution with pop for extract column A : 提取列A pop更通用的解决方案:

df = pd.DataFrame({'A':['a,b,c','b,c,f'], 'B':[3,4], 'C':[7,3]})
print (df)
       A  B  C
0  a,b,c  3  7
1  b,c,f  4  3

df1 = df.pop('A').str.get_dummies(',').astype(bool).join(df)
print (df1)
       a     b     c      f  B  C
0   True  True  True  False  3  7
1  False  True  True   True  4  3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将新列添加到 dataframe,其值取自另一个 dataframe? - How to add new columns to dataframe with value taken from another dataframe? 如何编写函数以在数据框中添加新列并基于现有列的值? - How to write functions to add new column in a dataframe and based out of the value from the exisiting columns? 如何仅为现有数据框的一列添加新日期和值 - How to add a new date and value for only one of the columns of an existing dataframe 如何将数据从一个 dataframe 添加到另一个 dataframe 上的新列 - how to add data from one dataframe to a new column on another dataframe 从具有不同值和类型的一列创建新的 dataframe 列 - Create new dataframe columns from one column with different values and types 熊猫:在数据框的最后一行添加一个具有单个值的新列 - Pandas: add a new column with one single value at the last row of a dataframe 将同一行从 pandas dataframe 多次添加到新行,每次更改特定列中的值 - Add the same row multiple times from a pandas dataframe to a new one, each time altering a value in a specific column 如何转置并添加具有从其中一列引用的值的新列 - How can I transpose and add a new column with a value referred from one of the columns 从现有数据框中创建新数据框,其中一列中的唯一值和其他列中的对应值 - Make new dataframe from existing dataframe with unique values from one column and corresponding values from other columns 将新列添加到 Pandas dataframe,其值来自 function - Add a new column to a Pandas dataframe with a value from a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM