[英]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 ![]() |
Column B ![]() |
---|---|
Cell 1![]() |
Valu 2![]() |
Cell w![]() |
Valu 8![]() |
Cell 3![]() |
Valu 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 ![]() |
Column J ![]() |
---|---|
cell 1![]() |
Data c![]() |
cell 3![]() |
Data 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 ![]() |
Column J ![]() |
Column C![]() |
---|---|---|
Cell 1![]() |
Data c![]() |
Valu 2![]() |
Cell 3![]() |
Data f![]() |
Valu 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.