Python /熊猫.多个数据框架上的For循环不能正常工作



我正在尝试使用for循环以多种方式处理数据帧列表(示例显示2,现实中有更多)。删除循环中引用的数据框中的列工作得很好,但是,concat在循环中不做任何事情。我希望更新dfs中引用的原始数据帧。

更新后的问题说明

前面的例子不包括这种情况/似乎不工作。示例:pandas dataframe concat使用for循环不起作用

将示例最小化会得到以下代码(部分借用另一个问题的代码)

import numpy as np
import pandas as pd

data = [['Alex',10],['Bob',12],['Clarke',13]]
data2 = ['m','m','x']
A = pd.DataFrame(data, columns=['Name','Age'])
B = pd.DataFrame(data, columns=['Name','Age'])
C = pd.DataFrame(data2, columns=['Gender'])
#expected result for A:
Anew=pd.DataFrame([['Alex','m'],['Bob','m'],['Clarke','x']], columns=['Name', 'Gender'])
dfs = [A,B]
for k, v in enumerate(dfs):
# The following line works as expected on A an B respectively, inplace is required to actually modify A,B as defined above
dfs[k]=v.drop('Age',axis=1, inplace=True)
# The following line doesn't do anything, I was expecting Anew (see above) 
dfs[k] = pd.concat([v, C], axis=1)
# The following line prints the expected result within the loop
print(dfs[k])
# This just shows A, not Anew: To me tha tmeans A was never updated with dfs[k] as I thought it would. 
print(A)

更新

试题:

data = [['Alex',10],['Bob',12],['Clarke',13]]
data2 = ['m','m','x']
A = pd.DataFrame(data, columns=['Name','Age'])
B = pd.DataFrame(data, columns=['Name','Age'])
C = pd.DataFrame(data2, columns=['Gender'])
Anew = pd.DataFrame([['Alex','m'],['Bob','m'],['Clarke','x']], columns=['Name', 'Gender'])
dfs = [A, B]
for v in dfs:
v.drop('Age', axis=1, inplace=True)
v['Gender'] = C
print(A)
print(Anew)
输出:

>>> A
Name Gender
0    Alex      m
1     Bob      m
2  Clarke      x
>>> Anew
Name Gender
0    Alex      m
1     Bob      m
2  Clarke      x

如果您使用inplace=True, Pandas不会返回DataFrame,因此dfs现在是None:

dfs[k]=v.drop('Age', axis=1, inplace=True)  # <- Remove inplace=True

试题:

dfs = [A, B]
for k, v in enumerate(dfs):
dfs[k] = v.drop('Age', axis=1)
dfs[k] = pd.concat([v, C], axis=1)
out = pd.concat([A, C], axis=1)
输出:

>>> out
Name  Age Gender
0    Alex   10      m
1     Bob   12      m
2  Clarke   13      x

相关内容

  • 没有找到相关文章

最新更新