edn*_*edn 3 python group-by dataframe pandas
我有以下熊猫数据框:
d2 = {'col1': [0, 0, 1, 1, 2], 'col2': [10, 11, 12, 13, 14]}
df2 = pd.DataFrame(data=d2)
df2
Run Code Online (Sandbox Code Playgroud)
输出:
col1 col2
0 0 10
1 0 11
2 1 12
3 1 13
4 2 14
Run Code Online (Sandbox Code Playgroud)
我需要运行以下命令:
for i, g in df2.groupby(['col1']):
col1_val = g["col1"].iloc[0]
print(col1_val)
Run Code Online (Sandbox Code Playgroud)
原始代码更复杂,但出于说明目的而编写。
该部分for i, g in df2.groupby(['col1']):给出了以下警告:
FutureWarning: In a future version of pandas, a length 1 tuple will be returned
when iterating over a groupby with a grouper equal to a list of length 1.
Don't supply a list with a single grouper to avoid this warning.
Run Code Online (Sandbox Code Playgroud)
我应该如何运行 for 循环来消除这个警告?
这意味着您应该使用字符串而不是具有唯一字符串的列表:
for i, g in df2.groupby('col1'):
col1_val = g["col1"].iloc[0]
print(col1_val)
Run Code Online (Sandbox Code Playgroud)
如果保留原来的代码,将来会有i值(0,)//而不是//(1,)(2,)012