我正在尝试根据列值访问某些行。我用
读取了 CSVdf = pd.read_csv("edges.txt", dtype=str)
创建以下 DataFrame:
TripId MatchId StartHour Source Destination
0 20120401017000 0 7 28819367 52408159
1 20120401017000 0 7 52408159 62804102
2 20120401017000 0 7 62804102 65398897
3 20120401017000 0 7 65398897 65398897
4 20120401017000 0 7 74066894 77482478
... ... ... ... ... ...
62014 20120430097008 1 18 78141321 88912706
62015 20120430097008 1 18 88912706 218287467
62016 20120430097008 1 18 218287467 236637429
62017 20120430097008 1 18 236637429 245325123
62018 20120430097008 1 18 245325123 245374827
当我使用特定 ID 访问行程时,它工作正常:
df.loc[df["TripId"] == "20120401017000"]
TripId MatchId StartHour Source Destination
0 20120401017000 0 7 28819367 52408159
1 20120401017000 0 7 52408159 62804102
2 20120401017000 0 7 62804102 65398897
3 20120401017000 0 7 65398897 74066894
4 20120401017000 0 7 74066894 77482478
... ... ... ... ... ...
86 20120401017000 2 7 330994406 484314696
87 20120401017000 2 7 484314696 502572843
88 20120401017000 2 7 502572843 758286629
89 20120401017000 2 7 758286629 791164312
90 20120401017000 2 7 791164312 974728472
但是,当我尝试访问具有特定 MatchId
的行时,它返回一个空的 DataFrame:
df.loc[df["MatchId"] == "2"]
TripId MatchId StartHour Source Destination
除了 TripId
之外的每一列都相同:
df.loc[df["Source"] == "283782532"]
TripId MatchId StartHour Source Destination
我对此有点困惑。 TripId
不是索引,而且它看起来没有任何特别之处。我确保每个值都是一个字符串:
df.dtypes
TripId object
MatchId object
StartHour object
Source object
Destination object
dtype: object
我有点困惑为什么除了 TripId
之外的每一列都返回一个空的 DataFrame。 TripId
不是索引,而且它看起来没有任何特别之处。
如何访问具有除 TripId
之外的列的特定值的行?
谢谢。
最佳答案
原则上,您的命令应该像 df["TripId"] 一样工作。您检查过前导/尾随空格吗?
any(char.isspace() for char in df.iloc[0][1])
关于python - Pandas - `loc` 在除一列之外的所有列上返回空 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878050/