簡體   English   中英

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

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

實現這種情況的最短方法是什么::

Dataframe1:(Dataframe1 Column A 有額外的值,因此我不能簡單地執行 df2["Column C"] = df["Column B"])

A列 B列
單元格 1 值 2
小區w 值 8
單元格 3 值 4

條件:在 Dataframe1 的 B 列中的 Dataframe2 的第 C 列(新列)插入值,其中 Dataframe1“Cell 1”中的列 A 的值與 Dataframe2“Cell 1”中的 X 列的值相匹配

Dataframe2 初始:(只有 X 列和 J 列)

X列 J欄
單元格 1 數據 c
單元格 3 數據f

Dataframe2 Final:(只有 X 列和 J 列,現在有符合上述條件的列 C)

X列 J欄 專欄C
單元格 1 數據 c 值 2
單元格 3 數據f 值 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

您可以使用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

在此之后你可以操作數據(刪除額外的列,重命名列)但是如果 df['Col A'] = df1['Col X] 這將幫助你將 'Col B' 放入 df1

這就是使用DataFrame.join(...)操作的方法。 您確實也可以使用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()

哪些輸出:

   X   B
0  1  b1
1  3  b3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM