What I want to do is something like:
for i, row in df.iterrows():
if row.at['Column'] == some_value:
some_other_df.append(row)
I can't seem to get this to work with the row object. It won't append like this, and it won't concatenate right with pd.concat()
Iterating through the rows creates a Series object, which is different from a DataFrame object, so it makes sense that it won't concatenate properly. Anyways, I'm looking for some method to be able to accomplish what the above pseudocode should.
CodePudding user response:
if you post the data as a code, it'll help in sharing the result from the solution.
this should help. try it out
some_other_df = df[df['Column'].eq(some_value)]
CodePudding user response:
You should probably filter or query instead of iterating.
import pandas as pd
df1 = pd.DataFrame(
[
[1, "Tom", 36, 3],
[2, "Bob", 30, 2]
],
columns=["ID", "Name", "Age", "Children"]
)
print(f"{df1}\n")
df2 = pd.DataFrame(
[
[3, "Joe", 23, 1],
[4, "Mike", 27, 4]
],
columns=["ID", "Name", "Age", "Children"]
)
print(f"{df2}\n")
filtered_df = df1.query("Name == 'Tom'")
final_df = pd.concat([df2, filtered_df], ignore_index=True)
print(final_df)