[英]How to loop through a pandas data frame using a columns values as the order of the loop?
[英]How to loop through pandas data frame and rename all of the columns?
我有一个 pandas 数据框,其中有几列我想重命名。
+------+--------------------------+--------------------------+--------------------------+
| FIPS | ('Active', '03/22/2020') | ('Active', '03/23/2020') | ('Active', '03/25/2020') |
+------+--------------------------+--------------------------+--------------------------+
| 1001 | 1 | 4 | 8 |
| 1003 | 4 | 6 | 9 |
| 1005 | 6 | 8 | 9 |
+------+--------------------------+--------------------------+--------------------------+
我想重命名第一列之后的所有列。 将 ('Active', '03/22/2020') 更改为 Active_20200322 等等。 这就是我希望我的最终 output 是:
+------+--------------------------+--------------------------+--------------------------+
| FIPS | Active_20200322 | Active_20200323 | Active_20200325
+------+--------------------------+--------------------------+--------------------------+
| 1001 | 1 | 4 | 8 |
| 1003 | 4 | 6 | 9 |
| 1005 | 6 | 8 | 9 |
+------+--------------------------+--------------------------+--------------------------+
有没有一种方法可以使用循环来做到这一点?
一种解决方案是编写 function 来修复列名。 然后你可以创建一个字典理解并将其传递给DataFrame.rename
来修复它们。 例如,像这样的东西:
import pandas as pd
import re
from datetime import datetime
def fix_column_name(val):
if 'Active' in val:
val = re.sub(r'[\(\)\']', '', val)
s1, s2 = re.split(',\s*', val)
s2 = datetime.strptime(s2, '%m/%d/%Y')
return f'{s1}_{s2.strftime("%Y%m%d")}'
return val
# Setup
df = pd.DataFrame({'FIPS': [1001, 1003, 1005],
"('Active', '03/22/2020')": [1, 4, 6],
"('Active', '03/23/2020')": [4, 6, 8],
"('Active', '03/25/2020')": [8, 9, 9]})
print(df)
[出去]
FIPS ('Active', '03/22/2020') ('Active', '03/23/2020') ('Active', '03/25/2020')
0 1001 1 4 8
1 1003 4 6 9
2 1005 6 8 9
d = {c:fix_column_name(c) for c in df.columns}
df = df.rename(d, axis=1)
print(df)
[出去]
FIPS Active_20200322 Active_20200323 Active_20200325
0 1001 1 4 8
1 1003 4 6 9
2 1005 6 8 9
将Index.map
与自定义mapper
function 一起使用,该映射器将输入参数作为列名,map 根据指定要求使用此名称:
import re
def mapper(c):
m = re.search(r"\('([^']+).*?'([^']+)'\)", c)
return "{0}_{3}{1}{2}".format(m.group(1), *m.group(2).split('/')) if m else c
df.columns = df.columns.map(mapper)
结果:
FIPS Active_20200322 Active_20200323 Active_20200325
0 1001 1 4 8
1 1003 4 6 9
2 1005 6 8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.