[英]How to create DataFrame in Python if values from list are in row of a different DataFrame?
I have a sample dataframe:我有一个样本 dataframe:
| ID | SampleColumn1| SampleColumn2 | SampleColumn3 |
|:-- |:------------:| ------------ :| ------------ |
| 1 |sample Apple | sample Cherry |sample Lime |
| 2 |sample Cherry | sample lemon | sample Grape |
I would like to create a new DataFrame based off of this initial dataframe. Should one of several values in a list [Apple, Lime, Cherry] be in any of the columns for a row, it would appear as a 1 in the new dataframe for its column.我想基于这个初始的 dataframe 创建一个新的 DataFrame。如果列表 [Apple、Lime、Cherry] 中的几个值之一位于一行的任何列中,它将在新的 dataframe 中显示为 1为其专栏。 In this case, the output should be:在这种情况下,output 应该是:
| ID | Apple | Lime | Cherry |
| 1 | 1 | 1 | 1 |
| 2 | 0 | 0 | 1 |
Currently I have tried in going about in using the find function for a string, transforming a series into a string for each row then using an if condition if the value has returned and equals the column name of the new dataframe. I am getting a logic error in this regard.目前,我已经尝试使用 find function 作为字符串,将系列转换为每一行的字符串,然后如果值已返回并等于新 dataframe 的列名,则使用 if 条件。我得到一个逻辑这方面的错误。
try this:尝试这个:
keywords = ['Apple', 'Lime', 'Cherry']
tmp = (df.melt(ignore_index=False)
.value.str.extract(
f'({"|".join(keywords)})',
expand=False)
.dropna())
res = (pd.crosstab(index=tmp.index, columns=tmp)
.rename_axis(index=None, columns=None))
print(res)
>>>
Apple Cherry Lime
1 1 1 1
2 0 1 0
You can create a function to replace strings that contain your desired substrings, then use pd.get_dummies()您可以创建一个 function 来替换包含所需子字符串的字符串,然后使用 pd.get_dummies()
fruits = ['Apple', 'Lime', 'Cherry']
def replace_fruit(string):
for fruit in fruits:
if fruit in string:
return fruit
return None
pd.get_dummies(df.set_index('ID').applymap(replace_fruit), prefix='', prefix_sep='').groupby(level=0, axis=1).sum().reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.