Python:使用带有局部函数的for循环将数据帧拆分为多个数据帧
Python: split dataframe into multiple dataframes by using for loop with locals function
我在下面有一个 csv 文件:
name,apply,percent
A,101,98%
B,388,79%
C,637,88%
D,541,75%
E,345,98%
A,446,85%
D,211,49%
我尝试将数据帧拆分为多个数据帧,如 df_A、df_B、df_C、df_D 和 df_E。
for name in df.groupby('name'):
locals()['df_'.name]=df[(df.name==name)]
print(df_A)
没用。如何修复代码?非常感谢。
你可以试试这个,
>>> import pandas as pd
>>> df = pd.read_csv('a.csv')
>>> for name in df['name'].unique():
... locals()['df_' + name] = df[(df.name == name)]
...
>>> df_A
name apply percent
0 A 101 98%
5 A 446 85%
>>> df_B
name apply percent
1 B 388 79%
>>> df_C
name apply percent
2 C 637 88%
>>> df_D
name apply percent
3 D 541 75%
6 D 211 49%
>>> df_E
name apply percent
4 E 345 98%
我在下面有一个 csv 文件:
name,apply,percent
A,101,98%
B,388,79%
C,637,88%
D,541,75%
E,345,98%
A,446,85%
D,211,49%
我尝试将数据帧拆分为多个数据帧,如 df_A、df_B、df_C、df_D 和 df_E。
for name in df.groupby('name'):
locals()['df_'.name]=df[(df.name==name)]
print(df_A)
没用。如何修复代码?非常感谢。
你可以试试这个,
>>> import pandas as pd
>>> df = pd.read_csv('a.csv')
>>> for name in df['name'].unique():
... locals()['df_' + name] = df[(df.name == name)]
...
>>> df_A
name apply percent
0 A 101 98%
5 A 446 85%
>>> df_B
name apply percent
1 B 388 79%
>>> df_C
name apply percent
2 C 637 88%
>>> df_D
name apply percent
3 D 541 75%
6 D 211 49%
>>> df_E
name apply percent
4 E 345 98%