简体   繁体   English

Python Dataframe 根据另一列的值向新列添加值

[英]Python Dataframe add a value to new column based on value from another column

What is the shortest way to achieve this scenario::实现这种情况的最短方法是什么::

Dataframe1: (Dataframe1 Column A has additional Values because of which i can not simply perform df2["Column C"] = df["Column B"] ) Dataframe1:(Dataframe1 Column A 有额外的值,因此我不能简单地执行 df2["Column C"] = df["Column B"])

Column A A列 Column B B列
Cell 1单元格 1 Valu 2值 2
Cell w小区w Valu 8值 8
Cell 3单元格 3 Valu 4值 4

Condition: Insert Value at Column C (New column) of Dataframe2 from Column B of Dataframe1 where Column A's value from Dataframe1 'Cell 1' matches Column X's value from Dataframe2 'Cell 1'条件:在 Dataframe1 的 B 列中的 Dataframe2 的第 C 列(新列)插入值,其中 Dataframe1“Cell 1”中的列 A 的值与 Dataframe2“Cell 1”中的 X 列的值相匹配

Dataframe2 Initial: (Has only Column X & Column J) Dataframe2 初始:(只有 X 列和 J 列)

Column X X列 Column J J栏
cell 1单元格 1 Data c数据 c
cell 3单元格 3 Data f数据f

Dataframe2 Final: (Which had only Column X & Column J, now has Column C with above mentioned condition) Dataframe2 Final:(只有 X 列和 J 列,现在有符合上述条件的列 C)

Column X X列 Column J J栏 Column C专栏C
Cell 1单元格 1 Data c数据 c Valu 2值 2
Cell 3单元格 3 Data f数据f Valu 4值 4
for key, value3 in df['Column A'].iteritems():
        value2 = datetime.datetime.strptime(value3, '%m/%d/%Y').strftime('%Y-%m-%d')
        value2 = str(value2)
        for key2, value4 in df2['Column X'].iteritems():
            sep = ' '
            value = str(value4)
            stripped = value.split(sep, 1)[0]
            if value2 == stripped:
                x = df[df['Column A']==value3]['Column B'].values[0]
                df2['Column C'][key2] = x

You can use a merge to achieve the result that you want.您可以使用merge来获得所需的结果。

import pandas as pd
df = pd.DataFrame({'Col A':['Cell 1','Cell 3'],'Col B':['Cell 2','Cell 4']})
df1 = pd.DataFrame({'Col X':['Cell 1','Cell 3'],'Col Y':['Cell c','Cell F']})
df2 = df1.merge(df,left_on='Col X',right_on='Col A',how='inner') 
df2

After this you can manipulate the data(remove extra columns, rename columns) but this would help you get 'Col B' into df1 if df['Col A'] = df1['Col X]在此之后你可以操作数据(删除额外的列,重命名列)但是如果 df['Col A'] = df1['Col X] 这将帮助你将 'Col B' 放入 df1

This is how you can do it with DataFrame.join(...) operation.这就是使用DataFrame.join(...)操作的方法。 You can indeed also use the DataFrame.merge(...) method as well.您确实也可以使用DataFrame.merge(...)方法。

import pandas as pd

# definition of the dataframes
df = pd.DataFrame(columns=["A", "B"])
df.A = [1, 2, 3]
df.B = ["b1", "b2", "b3"]

df2 = pd.DataFrame(columns=["X"])
df2.X = [1, 3]

# join operation
df2_final = df2.set_index("X").join(df.set_index("A")).reset_index()

Which outputs:哪些输出:

   X   B
0  1  b1
1  3  b3

暂无
暂无

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

相关问题 如何根据另一个 dataframe 的匹配为 dataframe 的新列添加值? - how to add value to a new column to a dataframe based on the match of another dataframe? Python Pandas dataframe - 根据索引值添加新列 - Python Pandas dataframe - add a new column based on index value Pandas:添加新列并按条件从另一个dataframe赋值 - Pandas: Add new column and assigning value from another dataframe by condition Pandas Dataframe - 添加具有另一行值的新列 - Pandas Dataframe - Add a new Column with value from another row Python:根据另一列值从 DataFrame 中删除重复项 - Python: Remove duplicates from DataFrame based on another column value 从一个 dataframe 中查找值,并在新列中返回与另一个 dataframe 基于公共值的另一列中最接近的值 - Lookup value from one dataframe and return in a new column the closest value from another column in another dataframe based on a common value Python:在DataFrame中,在新列中为另一列中具有最高值的行添加值,在第三列中添加相同的字符串 - Python: In DataFrame, add value in a new column for row with highest value in another column and string identical in a third one Python-根据条件将一列添加到包含来自另一行的值的数据框 - Python - Add a column to a dataframe containing a value from another row based on condition 根据来自不同 dataframe 的另一列,将值更新到当前 dataframe 中的新列 - Update the value into new column in current dataframe based on another column from different dataframe 根据来自另一个 dataframe 列的值选择列值 - Selecting a column value based on the value from another dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM